【问题标题】:connect tables with composite keys using code first fluent api使用 code first fluent api 使用复合键连接表
【发布时间】:2015-09-08 11:56:17
【问题描述】:

我有 2 个实体:

    //Product (all properties is the composite key)
    public string Id {get; set;}
    public string CompanyName {get; set;}

    //ProductDescriptions (All properties is the composite key)
    public string ProductId {get; set;}
    public string CompanyName {get; set;}
    public string Language {get; set;}

所以每个实体中的所有属性都构成了复合键。 我想要做的是使用代码优先流利的 api 使用导航属性将产品映射到产品描述。 我尝试了很多不同的方法,使用 WithMany、WithOptionl、HasMany、HasOptional 函数将产品映射到产品描述或其他方式。 产品可以有很多产品描述,每个产品描述需要有一个产品。

我还在某处读到,您需要先使用其他实体中复合键的所有属性才能使用代码对其进行映射。 因此,在这种情况下,由于产品实体不包含语言属性,因此我不能在产品中使用产品描述的导航属性。

但是是否可以以另一种方式映射它?由于 productdescription 具有 product 复合键的所有属性。

【问题讨论】:

    标签: c# entity-framework ef-fluent-api


    【解决方案1】:

    在编写以下代码之前,请配置您的模型(导航属性等)。

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
        base.OnModelCreating(modelBuilder);
    
        modelBuilder.Entity<ProductDescriptions >()
            .HasKey(c => new {c.ProductId , c.CompanyName , c.Language });
         modelBuilder.Entity<Product >()
            .HasKey(c => new {c.Id , c.CompanyName });
    
        modelBuilder.Entity<Product>()
            .HasRequired(p => p.ProductDescriptions )
            .WithMany(c => c.Product)
            .HasForeignKey(p => new {c.CompanyName , c.Id  });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多