我有这个课程:
Public Class Customer
Public Property CustomerID As Integer
Public Property CustomerName As String
Public Property OrdersList As ICollection(Of Order)
End Class
Public Class Order
Public Property OrderID As Integer
Public Property CustomerID As Integer
Public Property OrderTotal As Decimal
Public Property OrderDetails As ICollection(Of OrderDetail)
Public Property OrderCustomer As Customer
End Class
Public Class OrderDetail
Public Property OrderDetailID As Integer
Public Property OrderID As Integer
Public Property ProductID As Integer
Public Property Price As Decimal
Public Property Quantity As Decimal
Public Property LineTotal As Decimal
Public Property OrderDetailOrder As Order
Public Property OrderDetailProduct As Product
End Class
Public Class Product
Public Property ProductID As Integer
Public Property ProductName As String
Public Property ProductPrice As Decimal
Public Property OrderDetails As ICollection(Of OrderDetail)
End Class
这是PUT方法
Function PutOrder(ByVal id As Integer, ByVal order As Order) As HttpResponseMessage
If ModelState.IsValid And id = order.OrderID Then
db.Entry(order).State = EntityState.Modified
Try
db.SaveChanges()
Catch ex As DbUpdateConcurrencyException
Return Request.CreateResponse(HttpStatusCode.NotFound)
End Try
Return Request.CreateResponse(HttpStatusCode.OK)
Else
Return Request.CreateResponse(HttpStatusCode.BadRequest)
End If
End Function
但执行时: db.Entry(order).State = EntityState.Modified 我有这个错误
发生了引用完整性约束违规:定义引用约束的属性值在关系中的主体和从属对象之间不一致。
谢谢大家
答案 0 :(得分:0)
这意味着
order.CustomerID != order.OrderCustomer.CustomerID
OrderDetail.OrderID != OrderDetail.OrderDetailOrder.OrderID
至少有一个OrderDetails OrderDetail.ProductID != OrderDetail.OrderDetailProduct.ProductID
至少有一个OrderDetails 在将order
附加到上下文之前,您必须确保这些值相等。
答案 1 :(得分:0)
我认为这是解决方案
Dim x = db.Orders.Include(Function(a) a.OrderDetails).Include(Function(o) o.OrderCustomer).FirstOrDefault
db.Entry(x).CurrentValues.SetValues(order)
谢谢你@Slauma,你的提示很有帮助