【问题标题】:EF Code first: Mapping of entities to existing database with intermediate tableEF 代码优先:使用中间表将实体映射到现有数据库
【发布时间】:2011-04-18 13:10:44
【问题描述】:

这是一个示例场景。我有一个由以下表格组成的现有数据库;

订单,带有字段OrderId(PK,int)

产品,具有字段 ProductId (PK, int), PriceId (FK, int)

OrdersProducts,包含字段 OrderProductId (PK, int), OrderId (FK, int), ProductId (FK, int), OrderingStatus (int)

价格,带字段PriceId(PK,int)

所有 PK 都是身份。

我的实体是;

public class Order
{
 [Key]
 public int OrderId { get; set; }
 public virtual IList<Product> Products { get; set; }
}

public class Product
{
 [Key]
 public int ProductId { get; set; }
 public string Name { get; set; }
 public int OrderingStatus { get; set; }

 public virtual Price Price { get; set;}

}

public class Price
{
 [Key]
 public int PriceId { get; set;}

}

这是我的映射; 命令;

  HasMany<Product>(x => x.Products)
    .WithMany()
    .Map(m =>
    {
      m.MapLeftKey("OrderId");
      m.MapRightKey("ProductId");
      m.ToTable("OrdersProducts", "dbo");
    });

产品;

Map(m =>
  {
    m.Properties(p => new
    {
      p.Name
    });
    m.ToTable("Products", "dbo");
  });

  Map(m =>
  {
    m.Properties(p => new
    {
      p.OrderingStatus
    });

    m.ToTable("OrdersProducts", "dbo");
  });

  HasRequired<Price>(x => x.Price)
    .WithMany()
    .Map(m => m.MapKey("PriceId"));

价格;

  ToTable("Prices", "dbo");

我在上下文中的映射无法做到这一点,有没有人可以帮助我朝着正确的方向前进。

我实际上在这里遇到了两种麻烦,首先是 OrderingStatus 到我的中间表的映射,其次我在连接我的表时遇到了问题,即“指定的架构无效。错误:...错误 0019:类型中的每个属性名称都必须是唯一的。属性名称“OrdersProductsId”已定义。'


【问题讨论】:

    标签: c# ef-code-first code-first entity-framework-4.1


    【解决方案1】:

    您的映射将不起作用 - 您无法将 OrderingStatus 映射到您的 Prodcut,因为它不在同一个表中,并且与 Product 没有一对一的关系。它位于具有一对多关系的单独表中。您必须将 OrdersProducts 公开为单独的实体,因为您的联结表包含您要使用的其他属性:

    public class Order
    {
        [Key]
        public int OrderId { get; set; }
        public virtual ICollection<ProductOrder> ProductOrders { get; set; }
    }
    
    public calss ProductOrder
    {
        [Key]
        public int OrderProductId { get; set; }
        public int OrderStatus { get; set; }
        public virtual Product { get; set; }
        public virtual Order { get; set; }
    }
    
    public class Product
    {
        [Key]
        public int ProductId { get; set; }
        public string Name { get; set; }
        public virtual Price Price { get; set;}
    }
    
    public class Price
    {
        [Key]
        public int PriceId { get; set;}
    }
    

    【讨论】:

    • 谢谢,我现在看清楚了,从一开始就意识到我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2016-10-11
    • 1970-01-01
    • 2013-12-19
    • 2011-08-08
    • 2014-08-31
    相关资源
    最近更新 更多