So I got a class called ObjectA it has many ObjectsB, the objects got a Id, to identify them but ALSO a language (enum, but it is actually saved as and INT and doesn t matter either for this case).
public class ObjectA
{
public int Id {get;set;}
public Language Language {get;set;}
... // and a list of objectA properties
public virtual ICollection<ObjectB> ObjectBs {get;set;}
}
public class ObjectB
{
public int Id {get;set;}
public Language Language {get;set;}
... // and a list of objectB properties
public ObjectA TheObjectA {get;set;}
}
Now I learned how to map them both as a primary key, I use fluent API for this. I know you can also use [Key] and [Column] attributes (which I don t use):
modelBuilder.Entity<ObjectA>().HasKey(a => new {a.Id, a.Languague})
modelBuilder.Entity<ObjectB>().HasKey(a => new {a.Id, a.Languague})
Now I tried a lot of stuff but I can’t seem to be able to connect them with each other. Anyone has an idea how I can fix this?
If the principal (
ObjectA) in a one-to-many relationship has a composite primary key the dependent (ObjectB) must have a foreign key that is composed of the same number of columns as well.I assume that the related objects A and objects B must have the same language. In that case you can make
ObjectB.Languagethe first part of the foreign key. (It’s part of the primary and foreign key inObjectBat the same time.) If you expose the second part of the FK as property in your model, it would look like this:(I believe you must swap
IdandLanguagefor the following to work.)And the mapping with Fluent API:
If the languages can be different introduce a separate FK property for the language:
…and map:
If the relationship is optional use
WithOptionalinstead ofWithRequiredand make the FK properties nullable:I you don’t want to have FK properties in your model you can use
MapKeywith Fluent API: