[英]Entity framework code first using navigation properties a Key
I have the following class in my Entity framework Code First context 我在我的实体框架Code First上下文中有以下类
public class DataBinding
{
[Key]
public DataSource Source
{ get; set; }
[Key]
public DataType Type
{ get; set; }
.....
}
Both DataSource
and DataType
are part of the same context, but when i try to create the database i get the following error 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.
DataSource
和DataType
都是同一个上下文的一部分,但是当我尝试创建数据库时,我得到以下错误: 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.
i have defined two keys why am i getting this error? 我已经定义了两个键为什么我会收到此错误?
The problem is you are using two complex type as PKs,which is not allowed. 问题是您使用两种复杂类型作为PK,这是不允许的。
Key
members can be only scalar properties directly in the entity. Key
成员可以只是实体中的标量属性。 Complex type is represented as complex property which is not supported. 复杂类型表示为不支持的复杂属性。 Check this discussion and this post .
选中此讨论这个职位 。
To solve your problem you could do something like this: 要解决您的问题,您可以执行以下操作:
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; }
//...
}
Total rewriting: 总改写:
If i understood well, you want to realize an entity with composite key based as foreign keys on other entities in the same context. 如果我理解得很好,您希望在同一上下文中的其他实体上实现具有基于外键的复合键的实体。 You can not link the entity directly, but you can link the primary keys of this entities following the example.
您无法直接链接实体,但可以按照示例链接此实体的主键。
composite key from foreign keys 来自外键的复合键
You must in this case write explicitly the primary keys of the entities that are foreign key in the (simple types) you want to introduce on your class, as in the example before, and then add the navigation property. 在这种情况下,您必须明确地写出要在类中引入的(简单类型)中的外键实体的主键,如前面的示例中所示,然后添加navigation属性。
When you build a composite key (in any case), you have to give an ordering to the keys. 在构建复合键(无论如何)时,必须对键进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.