【问题标题】:Entity Framework ICollection creates internal table实体框架 ICollection 创建内部表
【发布时间】:2017-02-08 11:47:51
【问题描述】:

首先使用 .NET Entity Framework 代码我有两个简单的模型:

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; }
}

创建第三个表,名称为:LocationCars

有没有自定义这个生成表的名字?

非常感谢

【问题讨论】:

    标签: c# .net entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

    是的,您必须使用FluentApi 来自定义多对多关系

    从头到尾

    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");
                            });
    }
    

    【讨论】:

      【解决方案2】:

      您可以手动创建多对多映射:

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

      【讨论】:

        猜你喜欢
        • 2021-02-19
        • 2017-04-03
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多