EF具有多对多关系的默认约定 . 无需创建具体的
映射类 . 您必须在"FirstTable"和"SecondTable" Class中包含导航属性,如下所示 .
public class FirstTable
{
public FirstTable()
{
secondTableProperties = new HashSet();
}
public int Id { get; set; }
public int MyProperty2 { get; set; }
public int MyProperty3 { get; set; }
public virtual ICollection secondTableProperties { get; set; }
}
public class SecondTable
{
public SecondTable()
{
FirstTableProperties = new HashSet();
}
public int Id { get; set; }
public int MyProperty2 { get; set; }
public int MyProperty3 { get; set; }
public virtual ICollection FirstTableProperties { get; set; }
}
从DBContext中删除映射类,仅包括上面两个类 . 构建并运行应用程序,EF将自动在SQL Server中创建Mapping表 . 通常,映射表仅包含其他两个表的主键 .
您可以使用Fluent API对创建的映射表进行一些控制
modelBuilder.Entity()
.HasMany(s => s.FirstTableProperties)
.WithMany(c => c.secondTableProperties)
.Map(cs =>
{
cs.MapLeftKey("FirstTableId");
cs.MapRightKey("SecondTableId");
cs.ToTable("ManyToManyTable");
});
如果您想使用具有其他属性的连接表,则上述多对多关系将无效 . 在这种情况下,您将必须创建两个一对多关系,如下所示 .
public class FirstTable
{
public int Id { get; set; }
public int MyProperty2 { get; set; }
public virtual ICollection manytomany { get; set; }
}
public class SecondTable
{
public int Id { get; set; }
public int MyProperty2 { get; set; }
public virtual ICollection manytomany { get; set; }
}
public ManyToManyTable
{
[Required]
[Key, Column(Order=0)]
public int firsttableid { get; set; }
[Required]
[Key, Column(Order=1)]
public int secondtableid { get; set; }
public int AdditionalProperty { get; set; }
public virtual FirstTable first { get; set; }
public virtual SecondTable Second { get; set; }
}