0

当我运行我的项目时使用代码优先的方法。在新用户注册时,实体框架是抛出此异常:运行时实体框架异常:参与关系的实体?

Additional information: Entities in 'ApplicationDbContext.IdentityUsers' participate in the 'ApplicationUser_UserDetails' relationship. 0 related 'ApplicationUser_UserDetails_Target' were found. 1 'ApplicationUser_UserDetails_Target' is expected.

的异常被抛出:

var manager = new UserManager(); 
var user = new ApplicationUser() { UserName = UserName.Text }; 
//This line At the time of creating user 
IdentityResult result = manager.Create(user, Password.Text); 

我创建的模式代码:

public class ApplicationUser : IdentityUser 
    { 
     public Nullable<DateTime> DateOfCreation { get; set; } 
     public Nullable<bool> IsActive { get; set; } 
     public Nullable<DateTime> LastLogin { get; set; } 
     public UserDetails UserDetails { get; set; } 
     public virtual ICollection<TaskSheetManagement> TaskSheet { get; set; } 
     public virtual ICollection<Projects> Projects { get; set; } 
    } 

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
    { 
     public ApplicationDbContext() 
      : base("DefaultConnection") 
     { 
     } 

     protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<IdentityUser>().HasKey(pk => pk.Id).ToTable("Users"); 
      modelBuilder.Entity<ApplicationUser>().HasKey(pk=>pk.Id).ToTable("Users"); 
      modelBuilder.Entity<UserDetails>().HasKey(pk => pk.UserDetailId).ToTable("UserDetails"); 
      modelBuilder.Entity<ApplicationUser>().HasRequired(p => p.UserDetails).WithRequiredPrincipal(c => c.ApplicationUser); 
      modelBuilder.Entity<ApplicationUser>() 
       .Property(t => t.UserName).IsRequired() 
       .HasMaxLength(14) 
       .HasColumnAnnotation("Index", 
       new IndexAnnotation(new IndexAttribute("U_Username", 1) { IsUnique = true })); 
      modelBuilder.Entity<UserDetails>() 
       .Property(t => t.Email).IsRequired() 
       .HasMaxLength(25) 
       .HasColumnAnnotation("Index", 
       new IndexAnnotation(new IndexAttribute("U_Email", 2) { IsUnique = true })); 
      base.OnModelCreating(modelBuilder); 
     } 
    } 

而且是UserDetails是:

public class UserDetails 
{ 
    public int UserDetailId { get; set; } 
    public string Name { get; set; } 
    public string Email { get; set; } 
    public string CountryName { get; set; } 
    public string Gender { get; set; } 
    public string Nic { get; set; } 
    public string ResidentAddress { get; set; } 
    public string CellNO { get; set; } 
    public string PhoneNo { get; set; } 
    public string Religion { get; set; } 
    public ApplicationUser ApplicationUser { get; set; } 
} 

我找不出这个例外与什么有关。我搜索谷歌和实施其他解决方案,但无法解决。请帮助。

回答

0

您已创建1:1关联,但1:1关联在Entity Framework中不以此方式工作。

1:1关联必须共享相同的主键。你定义这个的方式是两个1:M关联,并且它们相互冲突。

如果你想有一个1:1,那么你必须改变你的主键的UserDetails是ID,然后你必须给他们喜欢的东西一起映射:

modelBuilder.Entity<UserDetails>().HasRequired(x => x.ApplicationUser) 
      .WithRequiredDependent(x => x.UserDetails);