EF with many to many relation on the same table with another attributes

entity framework core many-to-many same table
ef core many to many to many
ef core navigation many-to-many
entity framework core 3.0 many-to-many
entity framework core cross reference table
entity framework core multiple relationships to same table
ef core one-to-many with join table
entity framework core many-to-many query

I could' t do a many to many relationship on the same table with ef code first. Is there anyone can help me? I have a Category class and a CategoryRelation class too. Categoy class has many Parent Categories and many Child Categories. But i have a extra prop as DisplayId in CategoryRelation. My classes are like following

Category:

 public class Category : Base
{
    #region Top Menu
    public int DisplayOrder { get; set; }
    public bool ShowOnTopMenu { get; set; }
    #endregion

    public bool ShowOnTopSelling { get; set; }
    [MaxLength(100)]
    public string Name { get; set; }

    #region Types
    public bool IsPieceType { get; set; }
    public bool IsGildingType { get; set; }
    public bool IsPaperType { get; set; }
    public bool IsSizeType { get; set; }
    public bool IsWeightType { get; set; }
    public bool IsCellophaneType { get; set; }
    public bool IsCuttingType { get; set; }
    public bool IsPrintingType { get; set; }
    #endregion

    public virtual ICollection<CategoryRelation> ChildCategoryList { get; set; }    
    public virtual ICollection<CategoryRelation> ParentCategoryList { get; set; }
    public virtual ICollection<Product> ProductList { get; set; }
    public virtual ICollection<WishList> WishList { get; set; }
    public virtual ICollection<Description> DescriptionList { get; set; }
    public virtual ICollection<Comment> CommentList { get; set; }
    public virtual ICollection<Image> ImageList { get; set; }
    public virtual ICollection<Template> TemplateList { get; set; }
    public virtual ICollection<PromotionCode> PromotionCodeList { get; set; }
}

CategoryRelation;

public class CategoryReletion : Base
    {
        #region Parent Category
        [ForeignKey("ParentCategory")]
        public int ParentId { get; set; }
        public Category ParentCategory { get; set; }
        #endregion

        #region Child Category
        [ForeignKey("ChildCategory")]
        public int ChildId { get; set; }
        public Category ChildCategory { get; set; }
        #endregion
        public int DisplayOrder { get; set; }
    }

Finally i'm getting this error;

Introducing FOREIGN KEY constraint 'FK_dbo.CategoryReletion_dbo.Category_ParentId' on table 'CategoryReletion' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.*

You can do exactly as you are told (I assume that your context is name MyContext)

public class MyContext: DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<CategoryReletion> CategoryReletions { get; set; }

      protected override void OnModelCreating( DbModelBuilder modelBuilder )
      {
         modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
         modelBuilder.Entity<CategoryReletion>()
            .HasRequired( c => c.ParentId)
            .WithRequiredDependent()
            .WillCascadeOnDelete(false);

         modelBuilder.Entity<CategoryReletion>()
            .HasRequired( c => c.ChildId)
            .WithRequiredDependent()
            .WillCascadeOnDelete(false);
      }

}

Entity Framework Recipe: Many To Many Relationship On The , Entity Framework Recipe: Many To Many Relationship On The Same Table This scenario arises the same entity is related to itself in a different role. properties to columns in a separate table that stores the relationships. Multiple foreign keys pointing to same table in Entity Framework 4.1 code first; 2 Foreign Keys as Primary Key using EF Core 2.0 Code First; EF multiple foreign key relationship on same primary key; but those are for one-to-many relationship. *sorry for my bad english

It worked with these codes;

       modelBuilder.Entity<CategoryRelation>()
              .HasKey(c => new { c.ParentId, c.ChildId });

        modelBuilder.Entity<CategoryRelation>()
              .HasRequired(c => c.ParentCategory)
              .WithMany(c => c.ChildCategoryList)
              .HasForeignKey(c => c.ParentId)
              .WillCascadeOnDelete(false);

        modelBuilder.Entity<CategoryRelation>()
            .HasRequired(c => c.ChildCategory)
            .WithMany(c => c.ParentCategoryList)
            .HasForeignKey(c => c.ChildId)
            .WillCascadeOnDelete(false);

Is there a better way to model a many-to-many relationship on the , EF tries to associate many-to-many tables with some parent table. properties to appear in the parent entity or my many-to-many tables were� EF 6 includes default conventions for many-to-many relationships. You need to include a collection navigation property at both ends. For example, the Student class should have a collection navigation property of Course type, and the Course class should have a collection navigation property of Student type to create a many-to-many relationship between them without any configuration, as shown below:

This happens because of the multiple many to many relationships.

and you have cascadeDelete On which means if you delete a row all the related rows will be deleted imagine how this works on multiple relationships, you may end with a delete order for a deleted row.

So to solve this you need to use FluentApi to turn CascadeDelete off

Entity Framework Core 2.0 many-to-many relationships same table, While many to many relationship with explicit join entity is implemented The join entity contains two reference navigation properties, but the main Another way is to leave the model as is, but map the WordSinonymEntity. In a many-to-many relationship, each row of data in one table is linked to many rows in the second table and vice versa. A many-to-many relationship occurs when multiple records in one table are associated with multiple records in another table. For example, a many-to-many relationship exists between Book and Category entities.

[SOLVED], EventUser with EventId & UserId // Cascade Delete is always true for Many to Many mapping. however, it doesn't delete entry in other table, it� The primary key for the join table is a composite key comprising both of the foreign key values. In addition, both sides of the many-to-many relationship are configured using the HasOne, WithMany and HasForeignKey Fluent API methods. This is sufficient if you want to access book category data via the Book or Category entities.

Entity Framework Many-to-Many Relationships, In a many-to-many relationship, each row of data in one table is linked to many records in one table are associated with multiple records in another table. the many-to-many relationship when a collection navigation properties are added in � The many-to-many relationship involves defining a third table (called a junction or join table), whose primary key is composed of the foreign keys from both related tables. In a one-to-one relationship, the primary key acts additionally as a foreign key and there is no separate foreign key column for either table.

Configure Many-to-Many Relationship in Code First, Learn how to configure many-to-many relationship between entities in EF 6 Strategy � Configure Domain Classes � Data Annotations Attributes Visit the Entity Relationship chapter to understand how EF manages one-to-one, Use Fluent API to customize a joining table name and column names, as shown below: Using Self Referencing Tables With Entity Framework Since we have a key referencing a another key on the same table we can classify this this as a self-referencing table. Now that we fully

Comments
  • I added almost what you wrote but there are some differents. When i wrote as here it's functionality was false.I mean when i called the category has child categories. It's ChildCategoryList was empty and they were in ParentCategoryList instead of ChildCategoryList . then i changed it a little and worked correctly
  • Good job figuring out. +1 from me.