【发布时间】:2024-01-19 17:22:02
【问题描述】:
我们正在尝试映射一些冗余关系,但一直无法找出外键、导航属性和模型构建器语句的完美组合。
这是一个简化的例子;我知道有些人可能会建议整体更改表结构,但我们遇到过几种需要这种配置的情况。
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
解决方案!?
对于如何正确配置实体或更改模型构建器映射以使这些实体和关系按我们预期的方式运行,您有什么建议。
【问题讨论】:
标签: .net entity-framework entity-framework-6 poco