2017-04-06 55 views
0

我正在使用EF6代碼首先進行數據庫遷移,並且我是初學者。我正在構建一個web api。在我的模型計劃中,我有一個User(Identity Framework)和一個具有多對多關係的Location類。 EF6自動創建了一個表LocationUser,但我想用一些額外的列來擴展這個表。但是,做到這一點的最佳方式是什麼?添加一列以加入表格EF6

當然,我已經搜索了一些解決方案,但我不確定什麼是最好的方法。

我可以編輯最後一次遷移Up方法並添加我想要的列,但我不確定這是否是最好的方法。在我看來,手動創建一個新的模型類也是一種可能性。

有誰能告訴我什麼是最好的方法,並闡述爲什麼?

User.cs

public class User : IdentityUser 
{ 
    public virtual ICollection<Location> Locations { get; set; } 
    // Other code for Identity Framework 
} 

Location.cs

public class Location 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public double Lat { get; set; } 
    public double Lng { get; set; } 

    public virtual ICollection<User> Users{ get; set; } 
} 

回答

1

您可以創建自己的UserLocation類,如下所示。

public class UserLocation 
{ 
    public int Id { get; set; } 
    public Location Location { get; set; } 
    public User User { get; set; } 
    //Extra fields you want can go here 
} 

然後在你的UserLocation類你會改變使用您的UserLocation類的鏈接。

例子:

public class User : IdentityUser 
{ 
    public virtual ICollection<UserLocation> Locations { get; set; } 
    // Other code for Identity Framework 
} 

也可以EntityTypeConfigurations添加到您的類來執行多對多的,下面將是一個User

public class UserConfiguration : EntityTypeConfiguration<User> 
{ 
    public UserConfiguration() 
    { 
     HasKey(x => x.Id); 
     HasMany(x => x.Locations); 
    } 
} 
2

在我看來,最好的辦法是在其上下文中使用fluet API遵循教程更好地理解:

樣品:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 

    modelBuilder.Entity<User>() 
       .HasMany<Location>(u => u.Locations) 
       .WithMany(l => l.Students) 
       .Map(ul => 
         { 
          cs.MapLeftKey("UserId"); 
          cs.MapRightKey("LocationId"); 
          cs.ToTable("UserLocation"); 
         }); 

} 

教程: http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

有關更新的模式,我總是創造新的遷移,以免危及行動的實際歷史。

+0

謝謝您的回答。但是,我如何添加一個額外的列到UserLocation? – EJW