gpt4 book ai didi

c# - 为非主键属性配置一对多外键

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

这可能是一个简单的问题,但在阅读了数小时的 Microsoft 文档后我还是没能弄明白。我的数据库中有以下 2 个模型(我简化了它们以便更好地理解):

public class Schedule
{
public int Id { get; set; }
...
public string Role { get; set; }
}

public class Roles
{
public int Id { get; set; }
...
public string RoleDisplay { get; set; }
}

我需要将 Schedule 模型中的 Role 字符串设置为与 RoleDisplay 键具有一对多关系的外键 角色模型。所以在 Schedule 中,我们可以有很多记录,其中 Role 单元格指向 Roles 表。

如果它是常规的 Id key ,我会添加

public Roles Roles { get; set; }

Schedule,EF会自动在Schedule表中生成相应的RoleID列。

问题是我没有处理主键并且键命名约定不符合标准

<TableName><ColumnName> 

我听说这可以在 Fluent API 中设置,比如:

modelBuilder.Entity<Schedule>()
.HasOne()
.WithMany()
.HasForeignKey();

但我没有弄清楚每个语句需要放在括号中的是什么。

你能帮帮我吗?

最佳答案

由于您在任何一个实体上都没有任何导航属性,因此您必须使用通用版本 HasOne<Roles>()指示外键指的是哪个表。一旦 EF 清楚了这一点,您就不需要将任何内容传递给 WithMany() .尝试以下 -

  1. 声明RoleDisplay作为 Roles 上的备用键-
modelBuilder.Entity<Roles>(e =>
{
e.HasKey(p => p.Id);
e.HasAlternateKey(p => p.RoleDisplay);
});
  1. Schedule 上配置外键时, 指定 Roles 上的哪个键它应该针对-
modelBuilder.Entity<Schedule>(e =>
{
e.HasKey(p => p.Id);
});
modelBuilder.Entity<Schedule>()
.HasOne<Roles>()
.WithMany()
.HasForeignKey(p => p.Role)
.HasPrincipalKey(p => p.RoleDisplay);

希望对您有所帮助。

关于c# - 为非主键属性配置一对多外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65908448/

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