c# - Entity Framework 和 OnModelCreating()

标签 c# entity-framework-5

我正在使用代码优先方法,我正在尝试更改 EF 如何创建我的表的行为。我有两个简单的类:

注意:我每次都删除并重新创建我的数据库。这在现实世界中不会发生,但为了测试,我试图拦截创建并强制 EF 按照我的设想创建数据库。

public class Person
{
  public int PersonId { get; private set; }
  public string Forename { get; set; }
}
public class Officer : Person
{
  public int OfficerId { get; private set; }
  public bool IsManager { get; set; }
}

在我的 OnModelCreating() 事件中,我有以下内容:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();


        modelBuilder.Entity<Person>().HasKey(x => x.PersonId);
        modelBuilder.Entity<Person>().ToTable("Person");
        modelBuilder.Entity<Officer>().HasKey<int>(x => x.OfficerId);
        modelBuilder.Entity<Officer>().ToTable("Officer");
    }

问题是当我创建数据库时,它创建的表是:

表:人 PersonId INT PK 名字 nvarchar(50)

表:官员 PersonId INT PK,FK IsManager 位 OfficerId 整数

在我看来,这看起来是错误的,因为它不符合传统的命名约定,即 TableNameId。

非常感谢对此的任何帮助。 提前致谢,Onam。

最佳答案

Entity Framework 忽略这一行...

modelBuilder.Entity<Officer>().HasKey<int>(x => x.OfficerId);

...因为您不能为派生实体单独定义键,只能为您在此处完成的基本实体 Person 定义键:

modelBuilder.Entity<Person>().HasKey(x => x.PersonId);

此键和相应的列名 PersonId 然后用于基础实体和派生实体的所有表。 Code-First 无法为派生表中的键列提供与基表中不同的名称。

派生实体 Officer 中的 OfficerId 被视为普通标量属性,它在表中显示为 OfficerId INT 而不是PK.

关于命名约定,您可能会争辩说 Officer 是一个 Person,因此调用键 可能有意义个人身份。好吧,这更像是一种面向对象的命名约定,而不是关系和表的观点。

关于c# - Entity Framework 和 OnModelCreating(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16654863/

相关文章:

c# - 重命名 ASP.NET Identity 表时出现重复的外键

c# - 用 "and"代替最后一个逗号的逗号分隔列表

c# - 屏幕闪烁问题

.net - Entity Framework 函数导入参数类型在从数据库更新模型时重置

mysql - Entity Framework 5 codefirst与mysql

debugging - 如何调试 EF5 在运行时生成的 SQL?

c# - 我如何检查属性在更新之前是否实际更改

c# - 允许对象移动的 WPF 容器

c# - LINQ to XML 后代中的后代

c# - 获取 WPF 控件的所有附加事件处理程序