Given this example, it appears that detaching a object from it's EntitySet does not detach all child entities, as advertised.
Here's the Model:
public class Order
{
[Key]
public int Id { get; set; }
public string OrderData { get; set; }
[Include]
[Association("Order_OrderDetail", "Id", "Order_Id")]
public IEnumerable<OrderDetails> Details { get; set; }
}
public class OrderDetails
{
[Key]
public int Id { get; set; }
public int Order_Id { get; set; }
public String OrderDetailData { get; set; }
}
Here's the DomainService:
public IQueryable<Order> GetOrders()
{
var orders = new[] {
new Order { Id = 1, OrderData="Order 1",
Details = new []
{
new OrderDetails { Id=1, Order_Id=1, OrderDetailData="Order 1 Detail 1"},
new OrderDetails { Id=2, Order_Id=1, OrderDetailData="Order 1 Detail 2"},
new OrderDetails { Id=3, Order_Id=1, OrderDetailData="Order 1 Detail 3"},
}
},
new Order { Id = 2, OrderData="Order 2",
Details = new []
{
new OrderDetails { Id=4, Order_Id=2, OrderDetailData="Order 2 Detail 1"},
new OrderDetails { Id=5, Order_Id=2, OrderDetailData="Order 2 Detail 2"},
new OrderDetails { Id=6, Order_Id=2, OrderDetailData="Order 2 Detail 3"},
}
}};
return orders.AsQueryable();
}
public IQueryable<OrderDetails> GetOrderDetails()
{
throw new NotImplementedException();
}
And finally here's the client side methods that demonstrate the issue:
private OrderContext LocalContext;
public MainPageViewModel()
{
if (!IsInDesignMode)
{
LocalContext = new OrderContext();
LocalContext.Load(LocalContext.GetOrdersQuery());
Orders = new PagedCollectionView(LocalContext.Orders);
DetachCommand = new RelayCommand<Order>(DetachAction);
}
}
public RelayCommand<Order> DetachCommand { get; private set; }
private void DetachAction(Order source)
{
try
{
LocalContext.Orders.Detach(source);
var newContext = new OrderContext();
newContext.Orders.Attach(source);
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
When the DetachAction method is called it sucessfully Detaches the instance that was passed in, but throws an exception when it tries to attach the instance to another DomainContext. The exception is: Entity 'OrderDetails: 1' cannot be attached to this EntityContainer because it is already attached to another EntityContainer.
Perhaps I don't understand what the documentation means when it says: If the entity is the root of a compositional hierarchy, all child entities will also be detached Is not the Order that was detached the root of a compositional hierarchy?
I think the key to the problem is misunderstanding the documentation:
If the entity is the root of a compositional hierarchy
Your Details
property is not compositional. However, you can easily make it so by adding the '[Composition]` attribute:
[Include]
[Association("Order_OrderDetail", "Id", "Order_Id")]
[Composition]
public IEnumerable<OrderDetails> Details { get; set; }