I want to map a many to may relationship using ONLY data annotations so this is my case.
Say I have the following table
Foo:
FooId int identity
FooName varchar(max) not null
Bar:
BarId int identity
BarName varchar(max) not null
FooBarRelationships
TheBarId int
TheFooId int
As you can see the junction table contains FK names different from source. In addition the name of the table is also different
My classes are as follows
[Table("Foo")]
public class Foo {
[Key]
public Int32 FooId { get; set; }
public String FooName { get; set; }
public IEnumerable<Bar> Bars { get; set; }
}
[Table("Bar")]
public class Bar {
[Key]
public Int32 BarId { get; set; }
public String BarName { get; set; }
public IEnumerable<Foo> Foos { get; set; }
}
How should I modify my classes using data annotations in order to tell that the table FooBarRelationships
is a junction table and TheBarId
is the foreign key from Bar
table and TheFooId
is the foreign key from Foo
table?
P.S.
Having navigation properties declared as IEnumerable<T>
, not as ICollection<T>
is essential.
I've tried to map it using the map class which looks as follows
public class BarMap : EntityTypeConfiguration<Bar> {
public BarMap() {
this.HasMany(t => t.Foos)
.WithMany(t => t.Bars)
.Map(m => {
m.ToTable("FooBarRelationships");
m.MapLeftKey("TheBarId");
m.MapRightKey("TheFooId");
});
}
}
this gives me the following error.
The type arguments for method 'System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Bar>.HasMany<TTargetEntity> (System.Linq.Expressions.Expression<System.Func<Bar, ICollection<TTargetEntity>>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
If there is a way to resolve this error without changing the type IEnumeralbe<T>
to ICollection<T>
, it is also welcomed.