2017-02-08 41 views
3

使用.NET實體框架代碼首先我有兩個簡單的模型:實體框架的ICollection創建內部表

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

有沒有辦法自定義這個生成的表的名稱?

非常感謝

回答

1

是的,你必須使用FluentApi定製許多一對多關係

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

您可以創建手動很多一對多的映射:

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