1

I know others have posted about this, but I can't find an answer that seems to match what my question is. Although I am super new to .net so I may just not understand something.

My site has a project object, which is owned by a particular user. The project has another model for extra info that other users can add.

My models are like:

Project

  • Project Owner FK
  • Other stuff

Information

  • Project FK
  • Info Owner FK
  • Other stuff

But I am getting error The referential relationship will result in a cyclical reference that is not allowed.

I think it is upset that I have a fk to a user in both project and info. But the users are different, so I can't get rid of one. Is there a way to tell it that?

Again, I am brand new to .net, so I'm hoping this isn't a silly question. I come from a django background, if that helps with explanation.

Code:

public class Information
{

    [HiddenInput(DisplayValue = false)]
    public int InfoID { get; set; }

    //user
    public virtual User User { get; set; }
    [Required(ErrorMessage = "This field is required.")]
    public int UserID { get; set; }

    //project
    public virtual Project Project { get; set; }
    [Required(ErrorMessage = "This field is required.")]
    public int ProjectID { get; set; }

}

public class Project
{
    [HiddenInput(DisplayValue = false)]
    public int ProjectID { get; set; }

    //user
    public virtual User User { get; set; }
    [Required(ErrorMessage = "This field is required.")]
    public int UserID { get; set; }

}

I removed all of the other non-relational fields, since those are not important.

lovefaithswing
  • 1,510
  • 1
  • 21
  • 37

1 Answers1

5

UserID is required for both entities and ProjectID is required for Information entity. This will create multiple cascading paths if you remove a User. User -> Information and User -> Project -> Information.

You have to map the relationships using Fluent API and specify for atleast one relationship that WillCascadeOnDelete(false)

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
                    .HasMany(u => u.Informations)
                    .HasRequired(i => i.User)
                    .HasForeignKey(i => i.UserID)
                    .WillCascadeOnDelete(false);
    }
}
Eranga
  • 32,181
  • 5
  • 97
  • 96