I have below model
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;}
}
I'm running on disconnected area (with service our disconnected from the Entity Framework context)
- I create a order and save to database
client:
service.CreateOrder(new Order() { OrderN="fksjdf1" });
server:
using(EfDbContext context = new EfDbContext())
{
context.Orders.Add(order);
context.SaveChanges();
}
- I need to add one or more OrderItems to previously added order
client:
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);
server:
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();
}
Error: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
Why I see this error? Why I not update this entity?
How can i use entity framework from disconnected area?
EDIT 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();
}
}