繁体   English   中英

使用流畅的映射在Entity Framework中一对多

[英]One to many in Entity Framework using fluent mapping

我正在尝试使用流利的API进行一对多地图绘制。 这是我的课

    public class Product : EntityBase
{
    public Product()
    {
        this.ProductArticles = new List<ProductArticle>();
    }

    [Key]
    public int ProductId { get; set; }
    public string Description { get; set; }
    public string ReportText1 { get; set; }
    public string ReportText2 { get; set; }
    public bool Standard { get; set; }
    public int ProductGroupId { get; set; }
    public decimal? Surcharge1 { get; set; }
    public decimal? Surcharge2 { get; set; }
    public decimal? Surcharge3 { get; set; }
    public decimal? Surcharge4 { get; set; }
    public decimal PriceIn { get; set; }
    public decimal PriceOut { get; set; }
    public decimal PriceArtisanIn { get; set; }
    public decimal PriceArtisanOut { get; set; }
    public decimal PriceTotalIn { get; set; }
    public decimal PriceTotalOut { get; set; }
    public decimal PriceTotalOutVat { get; set; }
    public decimal PriceAdjustment { get; set; }
    public bool Calculate { get; set; }
    public string Notes { get; set; }
    [ForeignKey("ProductGroupId")]
    public virtual ProductGroup ProductGroup { get; set; }

    public virtual ICollection<ProductArticle> ProductArticles { get; set; }
}

public class ProductArticle : EntityBase
{
    [Key]
    public int ProductArticleId { get; set; }
    public int ProductId { get; set; }
    public int ArticleId { get; set; }
    public decimal Qty { get; set; }
    public decimal PriceIn { get; set; }
    public bool Primary { get; set; }
    public virtual Product Product { get; set; }
    public virtual Article Article { get; set; }
}

现在我要从单个产品包括所有产品文章

这是我的地图

    public class ProductMap : EntityTypeConfiguration<Product>
{
    public ProductMap()
    {
        // Primary Key
        this.HasKey(p => p.ProductId);

        // Table & Column Mappings
        this.ToTable("Product");
        this.HasMany(p => p.ProductArticles)
            .WithOptional()
            .Map(p => p.MapKey("ProductId").ToTable("ProductArticle"));
    }

但这不起作用..请帮助:)

首先-按照惯例,EF将名称等于IdEntityTypeName + Id属性视为主键。 因此,您无需手动配置。

第二-如果您不希望表名是复数形式,只需从上下文中删除该约定,而不是为每个实体映射提供表名:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    base.OnModelCreating(modelBuilder);
}

最后一个EF足够聪明,可以定义具有诸如RelatedEntityTypeName + Id类的名称的外键。 因此,您在这里不需要任何流畅的配置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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