使用 Fluent API 设置具有 2 个关系的删除行为

Set Delete Behavior with 2 relationships using Fluent API

我在带有 EF 的 .NET Core 应用程序中使用 Fluent API。我有 2 个用户之间的 Chat 模型:

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; }
                
    }

问题是,如果其中一个用户被删除,我想删除聊天,但我无法在 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);

我收到以下错误:

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'.

是否有正确的方法来使用流利的方式来做我想做的事情API?

你必须修复关系

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