I found a following issue regarding EF5 running under .NET 4.0, in Model First approach: I have following auto-generated entity:
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
Notice entity is associated with Order entity and Employee entity by 1 (Order, Employee) to many (Notice) relationship.
Afterward, Order entity has also association with Employee entity: many (Order) to 1 (Employee) relationship.
Then, I expect the following unit test to fail, because of Notice entity relation to Employee entity violation (I don't assign notice1.employee navigation property):
<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
But in result test is passed. In Database, Notice->employee_id value is equal to Order->employee_id value, what is not expected, because these foreign keys may point to different Employee object. I expected that i have to set up notice1.employee navigation property myself, and I would like to get DbUpdateException
exception if i forget to do it.
What is the reason of this strange EF5 behavior?
Update:
CreateNewNotice()
and CreateNewOrderWithAllRequiredAndRelatedEntities()
implementation:
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