3

Using EF Code First i have the following, for example:

public class Blog
{
    public int BlogID { get; set; }
    public string Content { get; set; }
    public virtual User User { get; set; }
    public virtual ICollection<BlogMeta> BlogMeta { get; set; }
}

public class BlogMeta
{
    public int BlogMetaID { get; set; }
    public string Content { get; set; }
    public virtual User User { get; set; }
    public virtual Blog Blog { get; set; }
}

This successfully generates the tables Blog and BlogMeta and creates the foreign key relationship with the User table. After reading this i changed this to the following:

public class Blog
{
    public int BlogID { get; set; }
    public string Content { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }
    public virtual ICollection<BlogMeta> BlogMeta { get; set; }
}

public class BlogMeta
{
    public int BlogMetaID { get; set; }
    public string Content { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }
    public int BlogID { get; set; }
    public virtual Blog Blog { get; set; }
}

and now it doesn't work. It generates the tables and then throws the following error when trying to create the relationships:

Introducing FOREIGN KEY constraint 'BlogMeta_User' on table 'BlogMeta' may cause cycles or multiple cascade paths.

So what is the advantage of introducing the public int UserID and why does it fail when doing so?

EDIT: Ok, so i've come across this answer which outlines the difference between Independent Associations and Foreign Key Associations... which it turns out is what i was talking about. So this leaves the question, why does it throw the above error when using foreign key associations?

Community
  • 1
  • 1
Michael Willmott
  • 529
  • 1
  • 8
  • 21

1 Answers1

7

As Ladislav mentioned, you are defining multiple cascade paths for BlogMeta entity. You'd have to disable cascade for one of your relationships.

You can add the following method to your context class, to diable cascade for your User-BlogMeta relationship:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<BlogMeta>().HasRequired(bm => bm.User).WithMany().WillCascadeOnDelete(false);
    base.OnModelCreating(modelBuilder);
}  

You can indicate the other end of relationship (WithMany(u => u.BlogMetas)) if you have defined a colletion of BlogMeta in your User class.

Kamyar
  • 18,123
  • 8
  • 90
  • 164