我有休闲的模特
namespace Prometheus.Models { [Table("People")] public class Person : IPerson { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Name { get { return FirstName + " " + LastName; } set{} } public string Email { get; set; } public DateTime? LastModified { get; set; } } }
一个继承它的人
namespace Prometheus.Models { [Table("UserProfile")] public class UserProfile : Person { public string UserName { get; set; } public string CNP { get; set; } public virtual Faculty Faculty { get; set; } public bool? IsUSAMV { get; set; } public virtual ICollection<Result> Results { get; set; } public virtual ICollection<Project> Projects { get; set; } } }
和种子的方法
private void AddUser(string user, string password, SimpleMembershipProvider membership) { if (membership.GetUser(user, false) == null) { WebSecurity.CreateUserAndAccount(user, password, new { CNP = "1890531111111", IsUSAMV = true, }); } }
当我尝试在没有UserProfile扩展Person的情况下运行种子方法时,一切都很好,但是当它扩展时,我一直收到错误提示。
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.UserProfile_dbo.People_Id". The conflict occurred in database "PrometheusDb", table "dbo.People", column 'Id'. The statement has been terminated.
任何帮助将不胜感激谢谢。
我尝试将我的功能更新为
private void AddUser(string firstName,string lastName, string password, SimpleMembershipProvider membership) { var user = firstName + "." + lastName; if (membership.GetUser(user, false) == null) { var profile = new UserProfile() { Email = "test@email.com", FirstName = firstName, LastName = lastName }; _context.Users.Add(profile); _context.SaveChanges(); WebSecurity.CreateAccount(user, password); } }
但是现在我得到:- 更新条目时发生错误。 有关详细信息,请参见内部异常。System.Data.SqlClient.SqlException:当IDENTITY_INSERT设置为OFF时,无法为表’UserProfile’中的标识列插入显式值。
您在创建项目和对数据库进行完整性检查的顺序上遇到问题。我做过类似的事情,它涉及先保存用户,然后保存帐户。我的代码如下所示:
var user = new User { UserName = model.UserName, Organisation = userOrg }; this.repository.SaveUser(user); string token = WebSecurity.CreateAccount(model.UserName, model.Password, true);
注意使用CreateAccount而不是CreateUserAndAccount方法
CreateAccount
CreateUserAndAccount