Using Entity Framework, how can I add a foreign key on two models to reference each other

Viewed 1640

I have a ASP.NET MVC 5/C# project. In my project I have two models, Rule and MenuItem. MenuItem has a foreign key that references Rule. And Rule has a foreign key that references MenuItem.

Couple things worth mentioning, my model have a Prefix in the model name. Also, I am using database first approach.

I want to be able to get the MenuItem with the required rule using .Include(...) and also I want to be able to get the Rules with the MenuItem

Here are my models

[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; }
}

However, when I try to pull the menu-items including the required-rule, I get the following error

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 '*'.

I believe this error due to the circular references between my models. However, I need to be able to access both properties either way.

How can I fix this problem?

2 Answers
Related