Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set Delete Behavior with 2 relationships using Fluent API

I using Fluent API in my .NET Core app with EF. I have a model of Chat between 2 users:

public class Chat
    {     
        //(id, text...)

        public string InitiatorId { get; set; }
        public ApplicationUser Initiator { get; set; }

        
        public string InvitedId { get; set; }
        public ApplicationUser Invited { get; set; }            
    }

public class ApplicationUser 
    {     
        //(id...)

        public List<Chat> Chats{ get; set; }
                
    }

The problem is that I want to chat deleted if one of those users deleted and I can not declare it that way in my dbContext:

 builder.Entity<Chat>()
                .HasOne(x => x.Initiator)
                .WithMany(x => x.Chats)
                .OnDelete(DeleteBehavior.Cascade);
 builder.Entity<Chat>()
                .HasOne(x => x.Invited)
                .WithMany(x => x.Chats)
                .OnDelete(DeleteBehavior.Cascade);

I got following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Cannot create a relationship between ‘ApplicationUser.Chats’ and ‘Chat.Invited’ because a relationship already exists between ‘ApplicationUser.Chats’ and ‘Chat.Initiator’. Navigation properties can only participate in a single relatio
nship. If you want to override an existing relationship call ‘Ignore’ on the navigation ‘Chat.Invited’ first in ‘OnModelCreating’.

Is there a proper way to do what i want using fluent API?

>Solution :

you have to fix relations

public class ApplicationUser 
    {     
        //(id...)

        public virtual List<Chat> InitiatorChats{ get; set; }
        public virtual List<Chat> InvitedChats{ get; set; }
                
    }

builder.Entity<Chat>()
                .HasOne(x => x.Initiator)
                .WithMany(x => x.InitiatorChats)
                 .HasForeignKey(d => d.InitiatorId);
               
 builder.Entity<Chat>()
                .HasOne(x => x.Invited)
                .WithMany(x => x.InvitedChats)
                .HasForeignKey(d => d.InvitedId)
                .OnDelete(DeleteBehavior.Cascade);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading