Entity Framework - Error: define the key for entity type
Hallo everybody,
i have the following simple models.
public class A
{
public B B { get; set; }
public C C { get; set; }
}
public class B
{
public i开发者_C百科nt Id { get; set; }
}
public class C
{
public int Id { get; set; }
}
I get an error while i am trying to get the data:
System.Data.Edm.EdmEntityType: : EntityType 'A' has no key defined. Define the key for this EntityType.
Previous it was done via "RelatedTo". Has anybody a solution for this problem with the help of an example?
Thanks in advance!
Each entity in EF must have a primary key. It looks like A is junction table for many to many so you have multiple choices.
Remove A totaly and let EF handle many-to-many:
public class B
{
public int Id { get; set; }
public virtual ICollection<C> Cs { get; set; }
}
public class C
{
public int Id { get; set; }
public virtual ICollection<B> Bs { get; set; }
}
If you want A as entity you must either define additional key:
public class A
{
public int Id { get; set; }
public B B { get; set; }
public C C { get; set; }
}
or you must include FK properties for B and C and mark them both as composite primary key (should be in db as well):
public class A
{
public int bId { get; set; }
public int cId { get; set; }
public B B { get; set; }
public C C { get; set; }
}
Edit:
Mapping for the last solution
modelBuilder.Entity<A>.HasKey(a => new { a.bId, a.cId });
modelBuilder.Entity<A>.HasRequired(a => a.B)
.WithMany()
.HasForeignKey(a => a.bId);
modelBuilder.Entity<A>.HasRequired(a => a.C)
.WithMany()
.HasForeignKey(a => a.cId);
Anyway if your A looks exactly as you described without any other properties you are definitely doing it wrong. Mapping A is only needed when it contains anything else then navigation properties / FKs for modelling many-to-many relation.
精彩评论