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;
var details = orderItem.Item.ItemDetails.Where(i => i.DateEffective <= dateCreated)
.OrderByDescending(i => i.DateEffective)
.FirstOrDefault();
, . , , , .
, , . , , "", . . , , , .
, -.
!
. .