gpt4 book ai didi

c# - 使用 EF7 映射一对零或一

转载 作者:太空狗 更新时间:2023-10-30 01:16:08 25 4
gpt4 key购买 nike

我目前正在清理一个相当大的数据库。数据库的一部分具有一对零或一映射关系。具体来说:

User -> UserSettings

并非所有用户都会有用户设置,但没有用户就不可能存在用户设置。不幸的是,这些表已经存在。 用户 有一个 PK ID。 UserSettings 有一个 PK ID 和一个列 User_Id_Fk,此时它不是真正的 FK(没有定义关系)。

我正在修复该问题,并已通过 SQL 从数据库的角度进行了修复,并已通过测试进行了确认。 (添加了 FK 约束。在 User_Id_Fk 上添加了唯一约束。)这都是在 UserSettings 表上完成的。 (注意:我这里没有使用 EF Migrations,此时我必须手动编写 SQL。)

但是,我现在需要连接现有应用程序以正确处理这个新映射。该应用程序使用 ASP.NET Core 1.0 和 EF7。以下是现有数据模型的(简化)版本。

public class User
{
public int Id { get; set; }

public virtual UserSettings UserSettings { get; set; }
}

public class UserSettings
{
public int Id { get; set; }

[Column("User_Id_Fk")]
public int UserId { get; set; }

[ForeignKey("UserId")]
public virtual User User { get; set; }
}

我也有这个 Fluent Mapping:

builder.Entity<UserSettings>()
.HasOne(us => us.User)
.WithOne(u => u.User)
.IsRequired(false);

当我去运行应用程序并访问数据库中的这些项目时,我收到此错误,然后是一组神秘的消息,这些消息没有与我的应用程序直接相关的信息。

ArgumentNullException: Value cannot be null.
Parameter name: navigation
Microsoft.Data.Entity.Utilities.Check.NotNull[T] (Microsoft.Data.Entity.Utilities.T value, System.String parameterName) <0x10d28a650 + 0x00081> in <filename unknown>, line 0

经过研究,有人提到UserSettings类的ID必须与外键相同,像这样:

public class UserSettings
{
[Key, ForeignKey("User")]
public int Id { get; set; }

public virtual User User { get; set; }
}

我真的没有这个作为一个选项,因为数据库正在用于我目前无法控制的其他应用程序。那么,我被困在这里了吗?我是否只需要维护一个 1:many 映射(现在可能发生,尽管它还没有发生)并且对 1:0..1 映射没有适当的约束?

更新看看下面octavioccl的回答,我试了一下没有成功。但是,我随后从 UserSettings 中的映射中删除了 User(但我保留了 UserId)。据我所知,一切似乎都有效。然而,我真的很困惑这里发生了什么,不知道这是否是正确的答案,或者我只是走运。

最佳答案

删除数据注释并尝试使用这些配置:

builder.Entity<UserSettings>()
.Property(b => b.UserId)
.HasColumnName("User_Id_Fk");

builder.Entity<User>()
.HasOne(us => us.UserSettings)
.WithOne(u => u.User)
.HasForeignKey<UserSettings>(b => b.UserId);

来自 EF Core documentation :

When configuring the foreign key you need to specify the dependent entity type - notice the generic parameter provided to HasForeignKey in the listing above. In a one-to-many relationship it is clear that the entity with the reference navigation is the dependent and the one with the collection is the principal. But this is not so in a one-to-one relationship - hence the need to explicitly define it.

quoted link 中提供的示例(Blog-BlogImage) 与您要实现的目标几乎相同。

如果我上面显示的解决方案不起作用,那么您应该检查 User_Id_Fk 列是否允许 null。如果是这种情况,请将 FK 属性类型更改为 int?:

public class UserSettings
{
public int Id { get; set; }

public int? UserId { get; set; }

public virtual User User { get; set; }
}

关于c# - 使用 EF7 映射一对零或一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36508244/

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