Defining Self Referencing Foreign-Key-Relationship Using Entity Framework 7 Code First

Hamid Mosalla

I have an ArticleComment entity as you can see below:

public class ArticleComment
 {
    public int ArticleCommentId { get; set; }
    public int? ArticleCommentParentId { get; set; }

    //[ForeignKey("ArticleCommentParentId")]
    public virtual ArticleComment Comment { get; set; }
    public DateTime ArticleDateCreated  { get; set; }
    public string ArticleCommentName { get; set; }
    public string ArticleCommentEmail { get; set; }
    public string ArticleCommentWebSite { get; set; }
    public string AricleCommentBody { get; set; }

    //[ForeignKey("UserIDfk")]   
    public virtual ApplicationUser ApplicationUser { get; set; }
    public Guid? UserIDfk { get; set; }

    public int ArticleIDfk { get; set; }
    //[ForeignKey("ArticleIDfk")]   
    public virtual Article Article { get; set; }


}

I want to define a foreign key relationship in such a way that one comment can have many reply or child, I've tried to create the relationship using fluent API like this:

builder.Entity<ArticleComment>()
            .HasOne(p => p.Comment)
            .WithMany()
            .HasForeignKey(p => p.ArticleCommentParentId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired(false);

I followed the solution that was proposed here and here, but I get an error with the message:

Introducing FOREIGN KEY constraint 'FK_ArticleComment_ArticleComment_ArticleCommentParentId' on table 'ArticleComment' 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.

First I though by setting the OnDelete(DeleteBehavior.Restrict) this would go away, but the problem persist, also I've tried to use the data annotation [ForeignKey("ArticleCommentParentId")] as you can see the commented code in the ArticleComment definition, but it didn't work, I'd appreciate any though on this.

E-Bat

You are not modeling correctly your entity. Each comment needs a Set of replies, which are of type ArticleComment too, and each of those replies are the ones that point back to its parent (Note the added ICollection Replies property):

  public class ArticleComment
     {
        public ArticleComment()
        {
            Replies = new HashSet<ArticleComment>();
        }

        public int ArticleCommentId { get; set; }
        public int? ParentArticleCommentId { get; set; }
        public virtual ArticleComment ParentArticleComment{ get; set; }
        public virtual ICollection<ArticleComment> Replies { get; set; }

        //The rest of the properties omitted for clarity...
    }

...and the fluent Mapping:

modelBuilder.Entity<ArticleComment>(entity =>
{
    entity
        .HasMany(e => e.Replies )
        .WithOne(e => e.ParentArticleComment) //Each comment from Replies points back to its parent
        .HasForeignKey(e => e.ParentArticleCommentId );
});

With the above setup you get an open-ended tree structure.

EDIT: Using attributes you just need to decorate ParentArticleComment property. Take into account that in this case EF will resolve all the relations by convention.

[ForeignKey("ParentArticleCommentId")]
public virtual ArticleComment ParentArticleComment{ get; set; } 

For collection properties EF is intelligent enough to understand the relation.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Entity Framework 5 Code First Self-Referencing Relationship

From Dev

Entity Framework 5 Code First Self-Referencing Relationship

From Dev

Defining multiple Foreign Key for the Same table in Entity Framework Code First

From Dev

Entity framework code first cant create primary and foreign key relationship

From Dev

Entity Framework: How to specify the name of Foreign Key column on a self-referencing Parent-Child relationship?

From Dev

Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework

From Dev

Can I create a bidirectional foreign key relationship using Entity Framework Code First data annotations?

From Dev

Self Referencing in Entity Framework 6 Code First

From Dev

Delete entity with self-referencing foreign key using recursive function in Entity Framework

From Dev

Delete entity with self-referencing foreign key using recursive function in Entity Framework

From Dev

Get foreign key value using Entity Framework code first

From Dev

Entity Framework Code First Foreign Key issue

From Dev

Entity Framework Code First Foreign Key issue

From Dev

Foreign Key in Code First Entity Framework

From Dev

Entity Framework: Foreign Key in code first

From Dev

Entity Framework 6 -> External Service -> self referencing foreign key -> The INSERT statement conflicted with the FOREIGN KEY constraint

From Dev

Entity Framework 6 multiple table to one foreign key relationship code first

From Dev

Entity Framework Code First Self Referencing Parent Child with Payload

From Dev

Entity Framework Self Referencing Using Non-Primary Key Column

From Dev

Entity Framework Model First Self referencing

From Dev

Entity Framework Model First Self referencing

From Dev

Can you customise foreign key names in self referencing entities in entity framework?

From Dev

Self referencing foreign key

From Dev

Entity Framework Code First Foreign Key adding Index as well

From Dev

Entity Framework 6 Code First Foreign Key Without Corresponding Properties

From Dev

Entity Framework Code First and Firebird - Foreign Key name issue

From Dev

Entity Framework Code first adds unwanted foreign key column

From Dev

Entity Framework - Code first - Data annotations - Unnecessary foreign key columns

From Dev

Multiple Foreign Key for Same table in Entity Framework Code First

Related Related

  1. 1

    Entity Framework 5 Code First Self-Referencing Relationship

  2. 2

    Entity Framework 5 Code First Self-Referencing Relationship

  3. 3

    Defining multiple Foreign Key for the Same table in Entity Framework Code First

  4. 4

    Entity framework code first cant create primary and foreign key relationship

  5. 5

    Entity Framework: How to specify the name of Foreign Key column on a self-referencing Parent-Child relationship?

  6. 6

    Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework

  7. 7

    Can I create a bidirectional foreign key relationship using Entity Framework Code First data annotations?

  8. 8

    Self Referencing in Entity Framework 6 Code First

  9. 9

    Delete entity with self-referencing foreign key using recursive function in Entity Framework

  10. 10

    Delete entity with self-referencing foreign key using recursive function in Entity Framework

  11. 11

    Get foreign key value using Entity Framework code first

  12. 12

    Entity Framework Code First Foreign Key issue

  13. 13

    Entity Framework Code First Foreign Key issue

  14. 14

    Foreign Key in Code First Entity Framework

  15. 15

    Entity Framework: Foreign Key in code first

  16. 16

    Entity Framework 6 -> External Service -> self referencing foreign key -> The INSERT statement conflicted with the FOREIGN KEY constraint

  17. 17

    Entity Framework 6 multiple table to one foreign key relationship code first

  18. 18

    Entity Framework Code First Self Referencing Parent Child with Payload

  19. 19

    Entity Framework Self Referencing Using Non-Primary Key Column

  20. 20

    Entity Framework Model First Self referencing

  21. 21

    Entity Framework Model First Self referencing

  22. 22

    Can you customise foreign key names in self referencing entities in entity framework?

  23. 23

    Self referencing foreign key

  24. 24

    Entity Framework Code First Foreign Key adding Index as well

  25. 25

    Entity Framework 6 Code First Foreign Key Without Corresponding Properties

  26. 26

    Entity Framework Code First and Firebird - Foreign Key name issue

  27. 27

    Entity Framework Code first adds unwanted foreign key column

  28. 28

    Entity Framework - Code first - Data annotations - Unnecessary foreign key columns

  29. 29

    Multiple Foreign Key for Same table in Entity Framework Code First

HotTag

Archive