在我运行项目时使用代码第一种方法。在新用户注册期间,实体框架抛出此异常:
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 :(得分: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);