我有以下型号:
public class ApplicationUser : IdentityUser
{
public int? StudentId { get; set; }
public virtual Student Student { get; set; }
}
public class Student : BaseEntity
{
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public string CreatedById { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
}
正如您所看到的,我在Student和ApplicationUser之间有两个一对一的关系,因此在ModelCreating中我定义了以下内容:
modelBuilder.Entity<ApplicationUser>()
.HasOptional(u => u.Student)
.WithRequired(s => s.User);
生成数据库时,除了列名之外一切正常,我希望student中创建的列为UserId,但它会将UserId列创建为一个简单列,并为该关系创建另一列User_Id。
如何在Student中定义属性UserId是关系的属性?
答案 0 :(得分:1)
你想要做的是有一个显式定义和映射的外键,它看起来像这样:
modelBuilder.Entity<ApplicationUser>()
.HasOptional(u => u.Student)
.WithRequired(s => s.User)
.HasForeignKey(u => u.UserId);
如果没有明确指定,则按照[{PropertyName}_Id]
答案 1 :(得分:0)
您需要指明哪个外键与哪个导航属性相关:
public class Student : BaseEntity
{
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
public string CreatedById { get; set; }
[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }
}
https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships