【问题标题】:Entity Framework child class, now requires Id/Key?实体框架子类,现在需要 Id/Key?
【发布时间】:2015-06-15 20:24:21
【问题描述】:

我的实体框架模型中有一个子对象。像这样的

public MyModel() {
    public long Id { get; set; }
    public string Name { get; set; }
    public MyModelReference Reference { get; set; }
}

public MyModelReference() {
    public bool IsActive { get; set;}
    public bool Name { get; set;}
}

这很好用,在 SQL 中它创建了 1 个名为 MyModel 的表,其中我有以下列

身份证

名字

Reference_IsActive

Reference_Name

这很好,因为在我的类中,与我的 MyModelReference 类中的引用有关的所有内容都放在我的 MyModelReference 类中,我可以通过访问 MyModel 中的 Reference 属性来访问这些属性。干净整洁。

现在我的库中有其他模型,我想在 MyModel 和 MyOtherModel 之间添加一个链接,但由于这个属性是 Reference 特有的,我想将它添加到我的 MyModelReference 类中。所以我也把它改成这样

public MyOtherModel() {
    public long Id { get; set; }
    public string Name { get; set; }
}

public MyModelReference() {
    public bool IsActive { get; set;}
    public bool Name { get; set;}
    public long OtherModelId { get; set; }
    public MyOtherModel OtherModel { get; set; }
}

现在由于某种原因,当我这样做并运行命令时

-update-database

我收到这样的错误

EntityType 'ModelReference' 没有定义键。定义此 EntityType 的键。 ModelReferences:EntityType:EntitySet 'ModelReferences' 基于没有定义键的类型 'ModelReference'。

当父类定义了 Id/Key 时,为什么我必须向子类添加一个键?我是否设置错误?

我希望这个设置能给我一个包含以下列的表格

身份证

名字

Reference_IsActive

Reference_Name

Reference_OtherModelId

【问题讨论】:

  • 抱歉,不确定您的意思?我在使用自己的类型?
  • 按照惯例,没有指定主键的类型被视为复杂类型。在某些情况下,Code First 不会检测到复杂类型。请尝试将您的 MyModelReference 明确定义为复杂类型。在您的模型配置上添加:modelBuilder.ComplexType()
  • 转到您的上下文,找到 OnModelCreating(DbModelBuilder modelBuilder) 并添加 modelBuilder.ComplexType() 。

标签: c# asp.net .net entity-framework entity-framework-6


【解决方案1】:

如果您没有在类型 EF will infer by convention 上定义键,则该类型是复杂类型,就像 MyModelReference 一样。

很遗憾,您不能在复杂类型上建立关联/关系:

复杂类型不能参与关联。关联的两端都不能是复杂类型,因此不能在复杂类型上定义导航属性。

https://msdn.microsoft.com/en-us/library/vstudio/ee382831(v=vs.100).aspx

【讨论】:

  • 他的模型中没有导航属性。有一个复杂的类型。
  • 没有定义虚拟修饰符。
  • @ViniciusGonçalves:我最初的意思是
  • 看来我想要一个复杂类型的关联,这是不可能的。必须将 ComplexType 更改为存储在单独的表中。谢谢@ViniciusGonçalves
  • @ViniciusGonçalves:属性不需要virtual 作为导航属性,删除virtual 会禁用延迟加载。 (见this page
猜你喜欢
  • 2021-05-17
  • 2015-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多