【问题标题】:Entity Framework creating another column for One to One Relationship实体框架为一对一关系创建另一列
【发布时间】:2015-08-29 02:17:48
【问题描述】:

我有以下型号:

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 是关系的属性?

【问题讨论】:

  • 我认为您的实体配置不正确...学生必须退出 ApplicationUser,或者用户必须退出 Student...

标签: c# entity-framework entity-framework-6 ef-fluent-api


【解决方案1】:

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

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

如果您没有明确指定,则会按照[{PropertyName}_Id] 的命名约定创建一个自动生成的外键

【讨论】:

  • 有没有办法通过注解来配置它,还是只能使用流利的 api?
  • @Escobar5 您可以尝试在 UserId 之上添加 [Key] 和 [ForeignKey("User ")] ?
  • "如果您没有明确指定,则会按照 [{PropertyName}_Id] 的命名约定创建自动生成的外键",这并不完全正确。一对一关系中的约定是使用两个实体的 PK。只是因为存在第二个关系(CreatedBy),所以需要指定一个,否则它将遵循此命名约定,因为它隐含的是一对多。
【解决方案2】:

您需要指出哪个外键与哪个导航属性一起使用:

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

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2015-05-04
    相关资源
    最近更新 更多