在这个例子中,似乎从它的EntitySet中分离一个对象并不会像advertised那样分离所有子实体。
这是模型:
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; }
}
这是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();
}
最后,这是证明问题的客户端方法:
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);
}
}
当调用DetachAction方法时,它成功地分离传入的实例,但在尝试将实例附加到另一个DomainContext时抛出异常。例外是: 实体'OrderDetails:1'无法附加到此EntityContainer,因为它已附加到另一个EntityContainer。
也许我不明白文档的含义当它说: 如果实体是组合层次结构的根,则所有子实体也将被分离 分离的订单是否是分离层次结构的根源?
答案 0 :(得分:1)
我认为问题的关键是误解了文档:
如果实体是组合层次结构的根
您的Details
财产不具有组合性。但是,您可以通过添加'[Composition]`属性轻松实现:
[Include]
[Association("Order_OrderDetail", "Id", "Order_Id")]
[Composition]
public IEnumerable<OrderDetails> Details { get; set; }