简体   繁体   中英

Entity framework code first using navigation properties a Key

I have the following class in my Entity framework Code First context

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. 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. Key members can be only scalar properties directly in the entity. 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.

When you build a composite key (in any case), you have to give an ordering to the keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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