Roman
Roman

Reputation: 4513

EF5 Code first - Many to Many with extra fields

I'm trying to use the awsome EF5 with code first - where I need to make a many-to-many table with extra fields.

I've got a products table, orders table and need a table of products that are in orders with a "size" field.

What I've done is created a new class of "ProductOrder" that is the connection table between them, and made a reference.

It WORKS when creating a new order, but is not working when fetching an order - it doesn't get the connected orders (that are present in the DB after the insertion).

Ideas why? :)

My Classes are:

public class Order
{
    public int ID { get; set; }
    ...
    public ICollection<ProductOrder> Products { get; set; }
    public Order()
    {
        Products = new HashSet<ProductOrder>();
    }
}

public class Product
{
    public int ID { get; set; }
    public ICollection<ProductOrder> Orders { get; set; }
}

public class ProductOrder
{
    public int ID { get; set; }
    public int ProductID { get; set; }
    public int OrderID { get; set; }
    public int Size { get; set; }

    [ForeignKey("OrderID")]
    public Order order { get; set; }

    [ForeignKey("ProductID")]
    public Product product { get; set; }
}

and in onModelCreating

    modelBuilder.Entity<Order>()
        .HasMany(p => p.Products)
        .WithRequired(o => o.order)
        .HasForeignKey(o => o.OrderID);

    modelBuilder.Entity<Product>()
        .HasMany(o => o.Orders)
        .WithRequired(p => p.product)
        .HasForeignKey(p => p.ProductID);

Upvotes: 4

Views: 1362

Answers (2)

Rick B
Rick B

Reputation: 1166

From what I've seen, marking the navigational properties as virtual turns lazy loading on for those properties.

The other way to get this to work without lazy loading is to add .include() statements to your select. This tells EF to pull back the extra data that you want.

Upvotes: 0

Malcolm O&#39;Hare
Malcolm O&#39;Hare

Reputation: 5009

Your navigational properties need to be virtual

Upvotes: 3

Related Questions