EF - the Navigation property is null, even after the object is reloaded, but works when the program restarts

EDIT

I did some testing and found out that the navigation property of an element only works when placing a context / a new context is created.

        DataContext context = new DataContext();
        Order ord = context.Orders.FirstOrDefault();
        ord.OrderItem.Add(new OrderItem() { ItemId = 8, Quantity = 2, DateCreated = DateTime.Now });
        // At this point, both Order and Item navigation property of the OrderItem are null

        context.SaveChanges();
        // After saving the changes, the Order navigation property of the OrderItem is no longer null, but points to the order. However, the Item navigation property is still null.

        ord = context.Orders.FirstOrDefault();
        // After retrieving the order from the context once again, Item is still null.

        context.Dispose();
        context = new DataContext();
        ord = context.Orders.FirstOrDefault();
        // After disposing of the context and creating a new one, then reloading the order, both Order and Item navigation props are not null anymore

Can someone explain this to me?

EDIT END

In my program, the user has a list of orders to which he can add new orders. The user can also add order elements to the order, but this does not work properly, since the OrderItem → Item navigation property is null, even after saving and reloading the order.

OrderItem
---------
OrderId
ItemId
Quantity
DateCreated
---------
Item <- navigation property
Order

, , activeOrder orderModel, .

GetOrderDataFromView()..

        ...
        // Check for existing item, update if match found, add new item if not
        foreach (ItemViewObject oi in orderItems)
        {
            var existingOrderItem = activeOrder.OrderItem.Where(o => o.ItemId == oi.ItemId).SingleOrDefault();

            if (existingOrderItem != null)
            {
                existingOrderItem.Quantity = oi.Quantity;
            }
            else
            {
                activeOrder.OrderItem.Add(new OrderItem()
                {
                    ItemId = oi.ItemId,
                    Quantity = oi.Quantity,
                    DateCreated = DateTime.Now
                });
            }

orderModel...

    public void AddOrUpdate(Order order)
    {
        if (order.Id == 0)
        {
            context.Orders.Add(order);
        }

        context.SaveChanges();
    }

, , OrderSelectionChanged(). , orderModel (return context.Orders.Where...)...

        // Get values from selected order and populate controls
        if (view.OrderTable.SelectedRows.Count != 0)
        {
            OrderViewObject ovm = (OrderViewObject)view.OrderTable.SelectedRows[0].DataBoundItem;
            activeOrder = orderModel.GetById(ovm.OrderId);

            PopulateOrderItemTableControl();

PopulateOrderItemTableControl(), .

        foreach (OrderItem oi in activeOrder.OrderItem)
        {
            orderItems.Add(new ItemViewObject(oi));
        }

ItemViewObject orderItem . navigationItem.Item navigation null, ...

    public ItemViewObject(OrderItem orderItem)
    {
        dateCreated = orderItem.DateCreated;

        // Retrieve latest item details, with effective date older or equal to the creation date of the order item
        var details = orderItem.Item.ItemDetails.Where(i => i.DateEffective  <= dateCreated)
                                                        .OrderByDescending(i => i.DateEffective)
                                                        .FirstOrDefault();

, . , , , .

, , . , , "", . . , , , .

, -.

!

. .

+3
1

:

DataContext context = new DataContext();
Order ord = context.Orders.FirstOrDefault();
ord.OrderItem.Add(new OrderItem() {
    ItemId = 8, Quantity = 2, DateCreated = DateTime.Now });
// At this point, both Order and Item navigation property of the OrderItem
// are null
// Explanation: That clear because you don't set Order and Item property

context.SaveChanges();
// After saving the changes, the Order navigation property of the OrderItem
// is no longer null, but points to the order. However, the Item navigation
// property is still null.
// Explanation: SaveChanges internally fixes relationships with objects that are
// attached to the context. Order is attached, Item is not. That why only
// the Order property is set

ord = context.Orders.FirstOrDefault();
// After retrieving the order from the context once again, Item is still null.
// Explanation: Because the Order is already attached a new query won't replace
// it. The entity remains the same as before.

context.Dispose();
context = new DataContext();
ord = context.Orders.FirstOrDefault();
// After disposing of the context and creating a new one, then reloading the
// order, both Order and Item navigation props are not null anymore
// Explanation: In a new context the Order will be loaded as a proxy. So, now
// lazy loading will work and load the Item property

, OrderItem new:

ord.OrderItem.Add(new OrderItem() {
    ItemId = 8, Quantity = 2, DateCreated = DateTime.Now });

, , . , :

var newOrderItem = context.OrderItems.Create();
newOrderItem.ItemId = 8;
newOrderItem.Quantity = 2;
newOrderItem.DateCreated = DateTime.Now;

ord.OrderItem.Add(newOrderItem);

context.SaveChanges() Item ( ItemId). "" context.Orders.FirstOrDefault() , .

+17

All Articles