![](/img/trans.png)
[英]How do I create linked X entities for a X entity using Entity Framework Core 2.0
[英]How do I define an entity class to be shared as a collection across multiple entities using Entity Framework Core?
我在 ASP.NET 核心 Web ZDB974238714CA38DE634A7CE1D0 中使用帶有 PostGreSQL 的實體框架核心我很難定義一組實體,其中 Class A 和 Class B 包含 Class Z0D61F8370CAD1D4112F580B84D14E 的集合。
在數據庫遷移期間生成的結果表/列不是我所期望的。
考慮以下表定義:
public class Supplier
{
[Key]
public Guid SupplierId { get; set; }
public string SupplierName { get; set; }
public List<Commodity> Commodities { get; set; }
}
public class Consumer
{
[Key]
public Guid ConsumerId { get; set; }
public string ConsumerName { get; set; }
public List<Commodity> Commodities { get; set; }
}
public class Commodity
{
[Key]
public Guid CommodityId { get; set; }
public string CommodityName { get; set; }
}
這些類導致生成以下表/列:
Suppliers
SupplierId
SupplierName
Consumers
ConsumerId
ConsumerName
Commodities
CommodityId
CommodityName
ConsumerId
如何創建 model class 定義,以便生成的表/列保留這些關系? 有沒有辦法強制創建連接表?
我應該使用一組特定的類/字段注釋嗎?
public class Supplier
{
[Key]
public Guid SupplierId { get; set; }
public string SupplierName { get; set; }
public ICollection<Commodity> Commodities { get; set; }
}
public class Consumer
{
[Key]
public Guid ConsumerId { get; set; }
public string ConsumerName { get; set; }
public ICollection<Commodity> Commodities { get; set; }
}
public class Commodity
{
[Key]
public Guid CommodityId { get; set; }
public string CommodityName { get; set; }
[Foreignkey("Supplier")
public Guid SupplierId { get; set; }
public Supplier Supplier { get; set; }
[Foreignkey("Consumer")
public Guid ConsumerId { get; set; }
public Consumer Consumer{ get; set; }
}
為了更好地理解 ICollection 和 IList,我建議: ICollection vs List
這個網頁有一些關於與 EF 不同關系的好信息。 EF 一對多
根據默認約定,當一個屬性的名稱與相關實體的主鍵屬性匹配時,EF 將其作為外鍵屬性。 數據注解
鑒於這些是一對多關系,我們希望 Commodity 表指向 Supplier 和 Consumer 表。 您應該在商品 model 中顯式添加關系列:
public class Commodity
{
[Key]
public Guid CommodityId { get; set; }
public string CommodityName { get; set; }
public Guid SupplierId { get; set; }
public Supplier Supplier { get; set; }
public Guid ConsumerId { get; set; }
public Consumer Consumer { get; set; }
}
無需更改供應商和消費者模型。 此更改應將SupplierId
和ConsumerId
設置為外鍵,然后您應該能夠從任一方訪問關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.