我在 Model First 方法中发现了关于在 .NET 4.0 下运行的 EF5 的以下问题:我有以下自动生成的实体:
Partial Public Class Notice
Private _id As Integer
Public Property id As Integer
Get
Return _id
End Get
Friend Set(ByVal value As Integer)
_id = value
End Set
End Property
Public Property order_id As Integer
Public Property employee_id As Integer
Public Property sysdate As Datetime
Public Property content As String
Public Overridable Property order As Order
Public Overridable Property employee As Employee
End Class
通知实体与订单实体和员工实体通过1(订单,员工)对多(通知)的关系关联。
之后,Order 实体也与 Employee 实体有关联:many (Order) to 1 (Employee) 关系。
然后,我预计以下单元测试会失败,因为通知实体与员工实体违规的关系(我没有分配 notice1.employee 导航属性):
<TestMethod()>
<ExpectedException(GetType(DbUpdateException))>
Public Sub ShouldNotAllowSaveNoticeWithoutAssignedEmployee()
Dim notice1 = CreateNewNotice() ' returned entity has not set any relation
notice1.order= CreateNewOrderWithAllRequiredAndRelatedEntities()
DbContext.noticeSet.Add(notice1)
DbContext.SaveChanges()
End Sub
但在结果测试中通过了。在数据库中,Notice->employee_id 值等于 Order->employee_id 值,这是意料之外的,因为这些外键可能指向不同的 Employee 对象。DbUpdateException
我希望我必须自己设置 notice1.employee 导航属性,如果我忘记这样做,我想获得例外。
这种奇怪的 EF5 行为的原因是什么?
更新:
CreateNewNotice()
和CreateNewOrderWithAllRequiredAndRelatedEntities()
实施:
Protected Function CreateNewNotice(Optional ByVal suffix As Int32 = 1) As Notice
Dim notice1 = New Notice() With {
.sysdate = DateTime.Now,
.content = Description & suffix ' Description is constant, for testing purposes
}
Return notice1
End Function
Protected Function CreateNewOrderWithAllRequiredAndRelatedEntities(Optional ByVal suffix As Int32 = 1) As Order
Dim order1 = CreateNewOrder(suffix) ' returned entity has not set any relation
order1.employee = CreateNewEmployee(suffix)
order1.customer = CreateNewCustomerWithAllRequiredRelatedEntities(suffix)
order1.seller = CreateNewSeller(suffix)
For i As Integer = 1 To 3
order1.notices.Add(CreateNewNotice(i)) ' created notices have not initialized relations
Next
Return order1
End Function