gpt4 book ai didi

c# - EF6 FluentAPI,0 :1 Unidirectional

转载 作者:行者123 更新时间:2023-11-30 23:19:42 25 4
gpt4 key购买 nike

我花了过去三个小时试图解决这个问题,最后放弃了(我会解决这个问题)。但是......只是为了确定......是否没有办法在 EF6 Fluent API 中设置单向 0:1/1:1?

考虑:

CREATE TABLE LegacyUsers (
ID INT NOT NULL PRIMARY KEY,
UserName NVARCHAR(50),
EmployeeID INT NULL
)

CREATE TABLE Employees (
ID INT NOT NULL PRIMARY KEY,
EmployeeName NVARCHAR(50)
)

领域模型:

public class LegacyUser {
public int ID {get;set;}
public int? EmployeeID {get;set;}
public virtual Employee Employee {get;set;}
}

public class Employee {
public int ID {get;set;}
public string EmployeeName {get;set;}
}

“流利”(哈哈)API理论设置:

modelBuilder.Entity<LegacyUser>()
.HasOptional(x => x.Employee)
.WithForgeignKey(x => x.EmployeeID)

我已经研究了几个小时,并尝试了多种方法来配置它。由于我的努力,我得到了“列名已存在”验证错误或“无效列:Employee_ID”错误的返回(如果这是双向的,我可以很容易地修复这些错误,但这是一个或多或少的锁定模式)。我发现唯一会迫使它工作的是将它作为 1:M 关系进行尝试,这通过必须将域模型属性用作集合而不是简单的单一关系来摆脱整个“流畅性”属性(property)。

真的没有办法像我认为的那样容易吗?要求非常简单:根据遗留用户文件中的员工 ID 获取关联的员工对象(无需破坏模型或向数据库添加新字段)

(供引用):

One to zero-or-one with HasForeignKey

Unidirectional One-To-One relationship in Entity Framework

最佳答案

The only thing that I've found that would force it to work is to try it as a 1:M relationship, which throws off the whole "fluency" by having to use the domain model property as a collection rather than a simple, single property.

这确实是建立这种关系的唯一方法,如 Associations in EF Code First: Part 5 – One-to-One Foreign Key Associations 中所述。 .但是你误读了单向部分。幸运的是,“uni”部分是依赖端的单个导航属性 - 正是外键属性所在的位置。

所以你的模型没问题,你只需要这样设置:

modelBuilder.Entity<LegacyUser>()
.HasOptional(e => e.Employee)
.WithMany()
.HasForeignKey(e => e.EmployeeID)
.WillCascadeOnDelete(false);

关键部分是无参数的 WithMany 调用。

关于c# - EF6 FluentAPI,0 :1 Unidirectional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40136722/

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