![](/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.