gpt4 book ai didi

c# - 使用 Entity Framework ,如何在两个模型上添加外键以相互引用

转载 作者:太空狗 更新时间:2023-10-29 23:49:33 24 4
gpt4 key购买 nike

我有一个 ASP.NET MVC 5/C# 项目。在我的项目中,我有两个模型,RuleMenuItemMenuItem 有一个引用 Rule 的外键。 Rule 有一个引用 MenuItem 的外键。

有几件事值得一提,我的模型在模型名称中有一个前缀。另外,我正在使用数据库优先方法。

我希望能够使用 .Include(...) 获取具有所需规则的 MenuItem,并且我希望能够使用 MenuItem 获取规则

这是我的模型

[Table("Rules")]
public class PrefixRule
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }

[ForeignKey("Item")]
public int ModuleId { get; set; }
public string Name { get; set; }

public virtual PrefixMenuItem Item { get; set; }
}

[Table("MenuItems")]
public class PrefixMenuItem
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }

[ForeignKey("RequiredRule")]
public int? RequiredRuleId { get; set; }
public string Name { get; set; }

public virtual PrefixRule RequiredRule { get; set; }
}

但是,当我尝试拉取包含必需规则的菜单项时,出现以下错误

One or more validation errors were detected during model generation:MenuItem_RequiredRule_Target: : Multiplicity is not valid in Role 'MenuItem_RequiredRule_Target' in relationship 'MenuItem_RequiredRule'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

我认为这个错误是由于我的模型之间的循环引用造成的。但是,我需要能够以任何一种方式访问​​这两个属性。

我该如何解决这个问题?

最佳答案

如果你要走这条路,那么你必须通过用 [Key, ForeignKey("PrefixMenuItem")] 装饰它来在规则表的主键和外键中创建公共(public)字符串 Id

有关完整示例,请参阅本文:http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

更新示例:

public partial class Rule
{

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key, ForeignKey("Item")]
public string Id { get; set; }

[ForeignKey("Module")]
public int ModuleId { get; set; }
public string Name { get; set; }

public virtual MenuItem Item { get; set; }
public virtual Module Module { get; set; }
}

public partial class MenuItem
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }

public string Name { get; set; }

public virtual Rule RequiredRule { get; set; }
}

public partial class Module
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ModuleId { get; set; }

public string Name { get; set; }

}

关于c# - 使用 Entity Framework ,如何在两个模型上添加外键以相互引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44015703/

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