![](/img/trans.png)
[英]How do you create a many-to-many relationship in Entity Framework if the database doesn't have a linking table?
[英]How do you connect a 1 to many table
我有一個ASP.NET Core項目,該項目具有以下兩個表:City和Country。
public class City
{
[Key]
public int Id { get; set; }
public string CityName{ get; set; }
public string Region{ get; set; }
public int CountryID { get; set; }
public Country Country { get; set; }
}
public class Country
{
[Key]
public int Id { get; set; }
[Required]
public string CountryName{ get; set; }
[Required]
public string Continent{ get; set; }
[Required]
public string Capital{ get; set; }
[Required]
public int NumberOfPeople{ get; set; }
}
一個城市類繼承一個國家的外鍵,並且一個國家可以擁有多個城市,即1-(0..M)。 它們都來自同一個DbContext
。
我希望能夠單擊“國家/地區”索引頁面上的詳細信息頁面(顯示所有國家/地區,其屬性和選項),以便顯示國家/地區信息以及該國家/地區的所有城市,但我無法確定了解如何通過DbContext
連接兩個表。
如何將加載特定國家(地區)信息和特定ID以及內部所有城市的模型傳遞給詳細信息視圖
如果要在Country
包括所有City
,則需要從Country
到City
添加導航屬性(已配置關系的另一部分):
public class Country
{
...
public ICollection<City> Cities { get; set; }
}
這使您可以執行單個數據庫查詢以帶來所有結果,而不必進行手動聯接。
然后,您可以將其用作:
var country = await context.Countries
.Include(x => x.Cities)
.SingleAsync(x => x.ID == someId);
您可以使用查詢執行程序的非Async
版本,但是鑒於您使用的是ASP.NET Core應用程序,因此建議您不要這樣做。
一種方法是對字段使用屬性:
public class City
{
[Key]
public int Id { get; set; }
public string CityName{ get; set; }
public string Region{ get; set; }
public int CountryID { get; set; }
[ForeignKey("CountryID")]
public virtual Country Country { get; set; }
}
public class Country
{
[Key]
public int Id { get; set; }
[Required]
public string CountryName{ get; set; }
[Required]
public string Continent{ get; set; }
[Required]
public string Capital{ get; set; }
[Required]
public int NumberOfPeople{ get; set; }
[InverseProperty("Country")]
public virtual ICollection<City> Cities { get; set; }
}
有多種方法可以做到這一點。
首先,您應該聲明您的類,例如:
public class City
{
[Key]
public int Id { get; set; }
public string CityName{ get; set; }
public string Region{ get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class Country
{
[Key]
public int Id { get; set; }
[Required]
public string CountryName{ get; set; }
[Required]
public string Continent{ get; set; }
[Required]
public string Capital{ get; set; }
[Required]
public int NumberOfPeople{ get; set; }
public virtual ICollection<City> Cities { get; set; }
}
其次,您應該配置關系:
protected override void OnModelCreating(Modelbuilder modelBuilder)
{
modelBuilder.Entity<Country>()
.HasMany(c => c.Cities)
.WithRequired(e => e.Country)
.HasForeignKey(c => c.CountryId);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.