0

我试图通过使用流利的 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; }
}

现在我想从单个产品中包含所有 ProductArticles

这是我的映射

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

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

4

1 回答 1

0

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

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

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

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

于 2013-09-13T10:50:56.863 回答