Per
Per

Reputation: 1425

EF Code first: Mapping of entities to existing database with intermediate table

This is a sample scenario. I have an existing database consisting of tables as below;

Orders, with field OrderId (PK, int)

Products, with fields ProductId (PK, int), PriceId (FK, int)

OrdersProducts, with fields OrderProductId (PK, int), OrderId (FK, int), ProductId (FK, int), OrderingStatus (int)

Price with field PriceId (PK, int)

All PKs are identity.

My Entities are;

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

}

And here are my mappings; Order;

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

Product;

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

Price;

  ToTable("Prices", "dbo");

I can't get this right with my mappings in the context, is there anyone that can help me in the right direction.

I am actually having two kinds of trouble here, first the mapping of OrderingStatus to my intermediate table, second I have trouble connecting my tables, ie 'Schema specified is not valid. Errors: ... error 0019: Each property name in i a type must be unique. Property name ''OrdersProductsId" was already defined.'


Upvotes: 1

Views: 1824

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

Your mapping will not work - you can't map OrderingStatus to your Prodcut because it is not in the same table and it is not related by one-to-one relation to the Product. It is in separate table with one-to-many relation. You must expose OrdersProducts as separate entity because your junction table contains additional properties which you want to use:

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

Upvotes: 2

Related Questions