c# - Entity Framework 代码首先使用导航属性一个Key

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

我的 Entity Framework 代码优先上下文中有以下类

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

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

DataSourceDataType 都是同一上下文的一部分,但是当我尝试创建数据库时出现以下错误 EntityType 'DataBinding' has no键定义。为此 EntityType 定义键。 DataBindings: EntityType: EntitySet 'DataBindings' 基于未定义键的类型 'DataBinding'。 我已经定义了两个键,为什么会出现此错误?

最佳答案

问题是您使用两个复杂类型作为 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; }
   //...
}

关于c# - Entity Framework 代码首先使用导航属性一个Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28638419/

相关文章:

c# - 使用 CSOM 读取 Sharepoint 中的网站页面内容

c# - 使用 DocumentViewer 控件呈现 PDF?

c# - 添加页码参数时,Report Services 在本地报告的 visual studio 调试器中崩溃

c# - 使用 EF Code First 建模员工-助理关系

c# - 更改 Entity Framework 生成的中间表的表模式

c# - 为什么 VS 2017 建议用方法替换属性?

.net - Entity Framework 4.1中的外键

asp.net-mvc - MVC5应用程序: Create Identity User results in Invalid Model State?

entity-framework - 为什么使用自定义 DbInitializer 的 EntityFramework 6.1 索引不起作用?

c# - 手动添加迁移?