Home > Net >  Set Delete Behavior with 2 relationships using Fluent API
Set Delete Behavior with 2 relationships using Fluent API

Time:12-07

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:

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?

CodePudding user response:

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);
  • Related