繁体   English   中英

实体框架代码首先使用导航属性一键

[英]Entity framework code first using navigation properties a Key

我在我的实体框架Code First上下文中有以下类

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. 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. 我已经定义了两个键为什么我会收到此错误?

问题是您使用两种复杂类型作为PK,这是不允许的。 Key成员可以只是实体中的标量属性。 复杂类型表示为不支持的复杂属性。 选中此讨论这个职位

要解决您的问题,您可以执行以下操作:

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; }
   //...
}

总改写:

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

来自外键的复合键

在这种情况下,您必须明确地写出要在类中引入的(简单类型)中的外键实体的主键,如前面的示例中所示,然后添加navigation属性。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM