Entity Framework ICollection 创建内部 table

Entity Framework ICollection creates internal table

使用 .NET Entity Framework Code First 我有两个简单的模型:

public class Car
{
    public int CarId { get; set; }

    public ICollection<Location> Locations { get; set; }
}

public class Location
{
    public int LocationId { get; set; }

    public ICollection<Car> Cars { get; set; }
}

这样做会创建第三个 table,名称为:LocationCars

是否可以自定义生成的 table 的名称?

非常感谢

是的,您必须使用 FluentApi 来自定义 many-to-many 关系

来自 turorial

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Car>()
                .HasMany(c => c.Locations)
                .WithMany(l => l.Cars)
                .Map(cl =>
                        {
                        cl.MapLeftKey("CarId");
                        cl.MapRightKey("LocationId");
                        cl.ToTable("YOUR_TABLE_NAME");
                        });
}

您可以创建手动 many-to-many 映射:

modelBuilder.Entity<Car>()
    .HasMany(c => c.Locations)
    .WithMany()
    .Map(l => l.MapLeftKey("CarId").MapRightKey("LocationId").ToTable("TableNameHere"));