gpt4 book ai didi

.net - 如何在 Entity Framework (EF6) Code-First 中映射冗余关系

转载 作者:行者123 更新时间:2023-12-01 05:01:24 25 4
gpt4 key购买 nike

我们试图映射一些冗余关系,一直无法找出外键、导航属性和 ModelBuilder 语句的完美组合。

这是一个简化的例子;我意识到有些人可能会建议整体更改表结构,但是我们遇到了几种需要这种类型配置的情况。

简化图:
Diagram of simplified example

POCO 类(class):

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

解决方案!?

您对如何正确配置实体或更改模型构建器映射以便这些实体和关系按照我们的预期发挥作用有什么建议。

最佳答案

经过进一步的头脑 Storm ,我意识到从 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 ------------------'

关于.net - 如何在 Entity Framework (EF6) Code-First 中映射冗余关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com