Reputation: 153
I am using EF 4.1 code first and have problem updating Order entity, when the existing entity contains a not null collection of OrderList and user has removed a few of the existing and added a new order list.
I have the domain model as shown below
public class Order
{
public int Id { get; set;
public string Name { get; set;}
public ICollection<OrderList> OrderLists { get; set;}
}
public class OrderList
{
public int Id { get; set;}
public int OrderId { get; set;}
public string ItemDescription { get; set;}
public decimal Price { get; set;}
public virtual Order Order { get; set;}
}
This is the code i am using for updating the Order entity.
using (var context = new MyDbContext())
{
var order = context.Orders
.Include("OrderLists")
.FirstOrDefault(o => o.Id == orderId);
order.Name = "New name"; // this gets saved
order.OrderLists.Clear(); // Does not delete the existing order list items
order.OrderLists = new List<OrderList> { new OrderList { OrderId = order.Id, ItemDescription = "New Item" } }; // Does not create new list
context.Orders.Attach(order);
context.Entry<Order>(order).State = System.Data.EntityState.Modified;
context.ChangeTracker.DetectChanges();
context.SaveChanges();
}
Please some guide me on how I can acheive this using EF 4.1 code first?
Thanks Guru
Upvotes: 1
Views: 1503
Reputation: 39898
This should do the trick:
var order = context.Orders
.Include("OrderLists")
.FirstOrDefault(o => o.Id == orderId);
order.Name = "New name"; // this gets saved
foreach (var orderlist in order.OrderLists.ToList())
{
context.OrderLists.Remove(orderlist);
}
order.OrderLists.Clear();
order.OrderLists.Add(new OrderList { Id = order.Id, ItemDescription = "New Item" });
context.SaveChanges();
You need to delete the orderlist items individually and then clear the collection.
Upvotes: 1