【发布时间】:2016-09-21 16:10:22
【问题描述】:
使用基于 EF6 代码
我的实际实体没有改变,但添加了一个新的 DBSet 以允许直接查询导航属性。
如果我运行 Add-Migration,它会生成一个非空迁移,只为外键重命名一个奇怪的列。
public override void Up()
{
RenameColumn(table: "dbo.ConfigurationPropertyBases", name: "ConfigurationClass_Id", newName: "ConfigurationClass_Id1");
RenameIndex(table: "dbo.ConfigurationPropertyBases", name: "IX_ConfigurationClass_Id", newName: "IX_ConfigurationClass_Id1");
}
为什么会产生这样的迁移?
DbContext 的变化:
public class ConfigurationContext : DbContext
{
//(...)
public DbSet<ConfigurationPackage> Packages { get; set; }
public DbSet<ConfigurationPropertyBase> ConfigurationPropertyBases { get; set; }
// THIS WAS ADDED
public DbSet<ConfigurationClass> ConfigurationClass { get; set; }
}
db 模型:(我只显示相关的导航属性)。
public class ConfigurationPackage
{
public int Id { get; set; }
//(...)
public List<ConfigurationClass> Configurations { get; set; }
}
public class ConfigurationClass
{
public int Id { get; set; }
public List<ConfigurationPropertyBase> ConfigurationProperties { get; set; }
}
public abstract class ConfigurationPropertyBase
{
public int Id { get; set; }
public string Name { get; set; }
//(no navigation propeties here)
}
我有许多从 ConfigurationPropertyBase 继承的类,但它们都只包含简单的属性,如 int 或 string(没有导航属性),除了一个是:
public class ConfigurationPropertyComplex : ConfigurationPropertyBase
{
public ConfigurationClass ConfigurationClass { get; set; }
}
【问题讨论】:
-
能否也请您添加 ConfigurationPropertyBase 的代码。还给定的名称包含单词 Base 我会问您的模型中是否有 this 的派生类已更改。
-
其实我发现了一个变化。我编辑了这个问题。它不在模型类中,而是在 DbContext 中。问题仍然存在。为什么会产生这样的迁移?
-
EF 生成在数据库中存储关系所需的列,然后在您使用 POCO 时在 DbContext 内静默管理它们。因为您需要有某种方式来关联两个实体,所以 EF 将使用父实体的 PK 来定义子实体上的隐式外键。我会更新我的答案以匹配。
标签: c# entity-framework entity-framework-6