[英]One-to-many relationships with code-first Entity Framework
I'm trying to set up a one-to-many relationship (I think) using code-first Entity Framework. 我正在尝试使用代码优先的Entity Framework建立一对多关系(我认为)。
I have a ProductListing
object which can have many associated Country
objects. 我有一个
ProductListing
对象,该对象可以具有许多关联的Country
对象。 I had thought that I had set this up correctly, but my Countries
table has a reference column for ProductListing
. 我以为自己已经正确设置了,但是“
Countries
表中有一个ProductListing
的参考列。 This is a problem because although a ProductListing
can have a relationship with Country
, the Country
object should not be aware or reliant upon the ProductListing
object. 这是一个问题,因为尽管
ProductListing
可以与Country
,但是Country
对象不应意识到或依赖于ProductListing
对象。
ProductListing 产品清单
public class ProductListing : AuditedEntity<long>
{
public long ProductId { get; set; }
public Product Product { get; set; }
public long RetailerId { get; set; }
public Retailers.Retailer Retailer { get; set; }
public ICollection<Countries.Country> Countries { get; set; }
public bool IsOfficial { get; set; }
public decimal CurrentPrice { get; set; }
public decimal PreviousPrice { get; set; }
public string ListingUrl { get; set; }
public string AffiliateString { get; set; }
public DateTime? ReleaseDate { get; set; }
public DateTime? ShipDate { get; set; }
public DateTime? ExpiresDate { get; set; }
}
Country 国家
public class Country : AuditedEntity<long>
{
[Required]
[StringLength(ShylockConsts.MaxNameLength)]
public virtual string Name { get; set; }
[Required]
[StringLength(ShylockConsts.MaxIsoLength)]
public virtual string IsoCode { get; set; }
}
What you actually have is a many-to-many
relationship where a Product can have many Countries, and a Country can have many Products. 您实际拥有的是
many-to-many
关系,其中一个产品可以有多个国家,一个国家可以有很多产品。
To model this, you will need an intermediate joining table to hold the Countries for each Product. 为了对此建模,您将需要一个中间联接表来保存每个产品的国家/地区。
Eg. 例如。
public class ProductCountry
{
[Required]
public virtual long ProductID { get; set; }
[Required]
public virtual long CountryID { get; set; }
}
Add a collection nav property to the Country
entity as well to model a many-to-many relationship as @Steve said (but there is no need to create an entity for the junction table in the conceptual model) 也可以将集合nav属性添加到
Country
实体中,以像@Steve所说的那样建立多对多关系的模型(但无需在概念模型中为联结表创建实体)
public class ProductList : ...
{
public ICollection<Country> Countries { get; set; }
}
public class Country : ...
{
public ICollection<ProductListing> ProductListings { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.