我们正试图映射一些冗余关系,并且无法找出外键,导航属性和ModelBuilder语句的完美组合。
这是一个简化的例子;我意识到有些人可能会建议整体改变表格结构,但我们遇到过几种需要这种配置的情况。
POCO课程:
Public Class Customer
<Key, Required>
Public Property CustomerID As Int32
Public Property Contacts As List(of Contact)
Public Property PrimaryContact As PrimaryContact
Public Class Contact
<Key, Required>
Public Property ContactID As Int32
<Required>
Public Property CustomerID As Int32
Public Property Customer As Customer
Public Property PrimaryContact As PrimaryContact
Public Class PrimaryContact
<Key, Required>
Public Property CustomerID As Int32
<Required>
Public Property ContactID As Int32
Public Property Customer as Customer
Public Property Contact as Contact
模型构建器尝试#1:
modelBuilder.Entity(Of Customer
).HasOptional(Function(C) C.PrimaryContact
).WithRequired(Function(PC) PC.Customer)
modelBuilder.Entity(Of Contact
).HasOptional(Function(C) C.PrimaryContact
).WithRequired(Function(PC) PC.Contact)
用法:
Dim NewCustomer As Customer 'Assigned Elsewhere'
Dim NewContact As Contact 'Assigned Elsewhere'
NewCustomer.PrimaryContact =
New PrimaryContact With {
.Contact = NewContact
}
问题:
我们的问题在于PrimaryContact表和关系/导航属性。
目前的问题是NewCustomer.PrimaryContact.Customer
在此作业后没有参考。
有一个次要问题,即使我们手动分配NewCustomer.PrimaryContact.Customer = Customer
,也有一个有效的引用,但EF不会连接插入内的ContactID
insert into "[SCHEMA]"."PRIMARYCONTACTS"("CUSTOMERID", "CONTACTID")
values (:p0, :p1)
-- :p0: '197467' (Type = Int32)
-- :p1: '0' (Type = Int32)
-- Executing at 9/1/2015 2:57:45 PM -04:00
-- Failed in 514 ms with error: ORA-02291: integrity constraint ([SCHEMA].PRIMARYCONTACTS_FK2) violated - parent key not found
解决方案!?
您对如何正确配置实体或更改模型构建器映射有何建议,以便这些实体和关系按照我们的预期运行。
答案 0 :(得分:1)
经过进一步的头脑风暴,我意识到从Contacts到PrimaryContact的导航属性实际上永远不会有用。事实证明它没有用,实际上是罪魁祸首。当我删除它和相应的ModelBuilder代码时,一切都开始工作
POCO课程
Public Class Contact
<Key, Required>
Public Property ContactID As Int32
<Required>
Public Property CustomerID As Int32
Public Property Customer As Customer
'-------------------- REMOVED --------------------'
' '
' Public Property PrimaryContact As PrimaryContact '
' '
'-------------------- REMOVED --------------------'
模型构建器
modelBuilder.Entity(Of Customer
).HasOptional(Function(C) C.PrimaryContact
).WithRequired(Function(PC) PC.Customer)
'------------------ REMOVED ------------------'
' '
' modelBuilder.Entity(Of Contact '
' ).HasOptional(Function(C) C.PrimaryContact '
' ).WithRequired(Function(PC) PC.Contact) '
' '
'------------------ REMOVED ------------------'