繁体   English   中英

与代码优先实体框架的一对多关系

[英]One-to-many relationships with code-first Entity Framework

我正在尝试使用代码优先的Entity Framework建立一对多关系(我认为)。

我有一个ProductListing对象,该对象可以具有许多关联的Country对象。 我以为自己已经正确设置了,但是“ Countries表中有一个ProductListing的参考列。 这是一个问题,因为尽管ProductListing可以与Country ,但是Country对象不应意识到或依赖于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; }
}

国家

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; }
}

您实际拥有的是many-to-many关系,其中一个产品可以有多个国家,一个国家可以有很多产品。

为了对此建模,您将需要一个中间联接表来保存每个产品的国家/地区。

例如。

public class ProductCountry
{
    [Required]
    public virtual long ProductID { get; set; }

    [Required]
    public virtual long CountryID { get; set; }
}

也可以将集合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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM