我有以下型号
public class Order
{
[Key]
public virtual string OrderNo {get;set;}
public virtual IList<OrderItem> Items {get;set;}
}
public class OrderItem
{
[Key]
public virtual string ItemNo {get; set;}
public virtual string ParentItemNo {get;set;}
public virtual string OrderNo {get;set;}
public virtual OrderItem ParentItem {get;set;}
public virtual IList<OrderItem> ChildItems {get;set;}
public virtual IList<ItemProperty> ItemProperties {get;set;}
public virtual Order Order {get;set;}
}
public class ItemProperty
{
[Key]
public virtual string PropertyNo {get; set;}
public virtual string ParentPropertyNo {get;set;}
public virtual string OrderItemNo {get;set;}
public virtual ItemProperty ParentProperty {get;set;}
public virtual IList<ItemProperty> ChildProperties {get;set;}
public virtual OrderItem OrderItem {get;set;}
}
我在断开连接的区域运行(服务与实体框架上下文断开连接)
- 我创建一个订单并保存到数据库
客户:
service.CreateOrder(new Order() { OrderN="fksjdf1" });
服务器:
using(EfDbContext context = new EfDbContext())
{
context.Orders.Add(order);
context.SaveChanges();
}
- 我需要在之前添加的订单中添加一个或多个 OrderItem
客户:
var order = service.GetOrder("fksjdf1");
var item1 = new OrderItem();
item1.ItemNo="i1";
item1.Order=order;
item1.OrderNo=order.OrderNo;
item1.ItemProperties.Add(new ItemProperty()
PropertyNo="p1",
OrderItem = item1
})
order.Items.Add(item1);
var item2 = new OrderItem();
item2.ItemNo="i2";
item2.Order=order;
item2.OrderNo=order.OrderNo;
item2.ItemProperties.Add(new ItemProperty()
PropertyNo="p2",
OrderItem = item2
});
item2.ItemProperties.Add(new ItemProperty()
PropertyNo="p3",
OrderItem = item2
})
order.Items.Add(item2);
service.UpdateOrder(order);
服务器:
using(EfDbContext context = new EfDbContext())
{
DbEntityEntry dbEntityEntry = context.Entry(order);
if (dbEntityEntry.State == EntityState.Detached)
{
// ERROR
context.Set<Order>().Attach(order);
}
dbEntityEntry.State = EntityState.Modified;
context.SaveChanges();
}
错误:发生引用完整性约束冲突:定义引用约束的属性值在关系中的主体对象和依赖对象之间不一致。
为什么我看到这个错误?为什么我不更新这个实体?
如何从断开连接的区域使用实体框架?
编辑1:
public Order GetOrder(string orderNo)
{
using (EfDbContext context = new EfDbContext())
{
context.Configuration.ProxyCreationEnabled = false;
var order = context.Orders
.Include(o => o.OrderItems
.Select(z => z.ItemProperties
.Select(y => y.ChildProperties)))
.Where(o => o.OrderNo == orderNo)
.FirstOrDefault();
}
}