Entity Framework 为一对一关系创建另一列

Entity Framework creating another column for One to One Relationship

我有以下型号:

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);

生成数据库时,除了列名外,一切都很好,我希望在学生中创建的列是 UserId,但它将列 UserId 创建为一个简单的列,并创建了另一个列 User_Id为了关系。

如何定义 Student 中的 属性 UserId 是关系的 属性?

你想要做的是有一个明确定义和映射的外键,它看起来像这样:

modelBuilder.Entity<ApplicationUser>()
            .HasOptional(u => u.Student)
            .WithRequired(s => s.User)
            .HasForeignKey(u => u.UserId);

如果您没有明确指定,则会按照 [{PropertyName}_Id]

的命名约定创建一个自动生成的外键

您需要指出哪个外键对应哪个导航 属性:

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