Peter
Peter

Reputation: 38515

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. i have defined two keys why am i getting this error?

Upvotes: 1

Views: 647

Answers (2)

ocuenca
ocuenca

Reputation: 39346

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

Upvotes: 2

Leonardo Festa
Leonardo Festa

Reputation: 101

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.

Upvotes: 1

Related Questions