简体   繁体   中英

Entity Framework 4.1: How can I access virtual entity properties after creating a new entity?

Here is my simplified code:

// Domain models
public class Order
{
    public int ID { get; set; }
    public int CustomerID { get; set; }
    public virtual ICollection OrderLineItems { get; set; }
    public virtual ICollection Transactions { get; set; }

    public void CreatePurchaseDebit()
    {
        var purchaseDebit = new Transaction()
        {
            Amount = OrderLineItems.Select(x => x.Product)
                         .Sum(x => x.Price) * -1
        };
        Transactions.Add(purchaseDebit);
    }
}

public class OrderLineItem
{
    public int ID { get; set; }
    public int OrderID { get; set; }
    public int ProductID { get; set; }
    public virtual Product Product { get; set; }
}

public class Product
{
    public int ID { get; set; }
    public decimal Price { get; set; }
}

// Repository
public class Repository
{
    public void Add(Order order)
    {
        context.Add(order);
        order.CreatePurchaseDebit(); // This throws an error
    }
}

The problem here is that when attempting to execute CreatePurchaseDebit() Product is null even though ProductID has been set accordingly by the user during the create process.

My hope was that adding the new Order to the DbContext would populate the virtual domain model properties via the associated foreign key ID. In the debugger I can see that Order has multiple OrderLineItems and that each OrderLineItem has a valid ProductID , however Product is null so I can't access the Product 's price!

So is there a way to tell Entity Framework to populate the virtual domain model properties or is my design bad?

PS: Even if I call SaveChanges() after adding adding the new Order to the DbContext Product is still null . I want to make sure the Order has a purchase debit before calling SaveChanges() so that it is not possible for an order to exist without a transaction.

Thanks!

Product will not be loaded just because you set up ProductId . If you creating new Order and you want to have order line items populated with products use products' ids to load products from database and assign them to order line items.

So instead of doing this:

var order = new Order
  {
    CustomerId = customerId,
    OrderLineItems = new List<OrderLineItme>
      {
        new OrderLineItem
          {
            ProductId = productId
          }
      }
  };

use this:

var product = context.Products.Single(p => p.Id == productId);
var order = new Order
  {
    CustomerId = customerId,
    OrderLineItems = new List<OrderLineItme>
      {
        new OrderLineItem
          {
            Product = product
          }
      }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM