【问题标题】:Entity framework code first using navigation properties a Key实体框架代码首先使用导航属性一个 Key
【发布时间】:2015-04-22 16:32:25
【问题描述】:

我的实体框架代码优先上下文中有以下类

public class DataBinding
{
    [Key]
    public DataSource Source
    { get; set; }

    [Key]
    public DataType Type
    { get; set; }
    .....
}

DataSourceDataType 都属于同一个上下文,但是当我尝试创建数据库时,出现以下错误 EntityType 'DataBinding' has no key defined. Define the key for this EntityType. DataBindings: EntityType: EntitySet 'DataBindings' is based on type 'DataBinding' that has no keys defined. 我定义了两个键,为什么会出现此错误?

【问题讨论】:

    标签: c# ef-code-first entity-framework-6


    【解决方案1】:

    问题是您使用两个复杂类型作为 PK,这是不允许的。 Key 成员只能是实体中直接的标量属性。复杂类型表示为不支持的复杂属性。 检查这个discussion和这个post

    要解决您的问题,您可以这样做:

    public class DataSource
    {
        public int Id { get; set; }
        //...
    }
    
    public class DataType
    {
        public int Id { get; set; }
        //...
    }
    public class DataBinding
    {
        [Key,ForeignKey("Source"),Column(Order = 0)]
        public int DataSourceId {get;set;}
        [Key,ForeignKey("Type"),Column(Order = 1)]
        public int DataTypeId {get;set;}
    
       public DataSource Source { get; set; }
    
       public DataType Type { get; set; }
       //...
    }
    

    【讨论】:

      【解决方案2】:

      全部重写:

      如果我理解得很好,您希望实现一个具有复合键的实体,该复合键基于同一上下文中其他实体的外键。 您不能直接链接实体,但您可以按照示例链接此实体的主键。

      composite key from foreign keys

      在这种情况下,您必须像之前的示例一样,在您要在类中引入的(简单类型)中明确写入作为外键的实体的主键,然后添加导航属性。

      当您构建复合键时(无论如何),您必须对键进行排序。

      【讨论】:

      • 看起来很丑但是我试试看!
      • sorry 错误的链接,看起来这个更容易,你只需要给钥匙下订单。索引将通过对第一个 (order = 0 ) 键进行排序来创建
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多