我有以下基于 EntityObject 的 EF 模型(属性写在这里作为保持代码更清洁的字段):
Booking
{
int BookingID;
EntityCollection<BookingCustomer> BookingCustomers;
string Notes;
}
BookingCustomer
{
Customer Customer;
Booking Booking;
int CustomerID;
int BookingID;
string Notes;
}
Customer
{
int CustomerID;
string Name;
}
我以分离的方式加载对象图:
Booking existingBooking;
using(MyContext ctx = new MyContext())
{
ctx.Bookings.MergeOption = MergeOption.NoTracking;
ctx.BookingCustomers.MergeOption = MergeOption.NoTracking;
ctx.Customers.MergeOption = MergeOption.NoTracking;
existingBooking = ctx.Bookings
.Include("BookingCustomers")
.Include("BookingCustomers.Customer")
.First();
}
修改预订和客户数据:
existingBooking.Notes = "Modified";
existingBooking.BookingCustomers.First().Name += " Edited";
保存它:
using(MyContext ctx = new MyContext())
{
ctx.Bookings.Attach(existingBooking);
ctx.ObjectStateManager.GetObjectStateEntry(existingBooking ).SetModified();
ctx.Refresh(RefreshMode.ClientWins, existingBooking);
ctx.SaveChanges();
}
我创建了一条新的客户记录(而不是更新了现有记录)。
我也试过这个:
using(MyContext ctx = new MyContext())
{
ctx.Customers.Attach(existingBooking.BookingCustomers.First());
ctx.ObjectStateManager.GetObjectStateEntry(existingBooking.BookingCustomers.First()).SetModified();
ctx.Refresh(RefreshMode.ClientWins, existingBooking.BookingCustomers.First());
ctx.Bookings.Attach(existingBooking);
ctx.ObjectStateManager.GetObjectStateEntry(existingBooking ).SetModified();
ctx.Refresh(RefreshMode.ClientWins, existingBooking);
ctx.SaveChanges();
}
但上线异常ctx.Customers.Attach(existingBooking.BookingCustomers.First());
:
System.InvalidOperationException: 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.
我怎样才能让它工作?