EF Core introducing foreign key constraint on table may cause cycles or multiple cascade paths

Viewed 26

I have a User entity:

public class User
{
    [Key]
    public string Username { get; set; }
}

and a Message entity:

public class Message
{
    public int Id { get; set; }

    public string Text { get; set; }
    
    public DateTime Date { get; set; }
    
    public User Sender { get; set; }
    
    public User? Recipient { get; set; }

}

and my context is configured like this:

public class DummyContext: DbContext
{
    public DummyContext(DbContextOptions<DummyContext> options)
        : base(options){ }

    public DbSet<Message> Messages { get; set; } = null!;

    public DbSet<User> Users { get; set; } = null!;
}

Everything works fine and i can add-migration and update-database

Then i try to add another Invoice entity:

public class Invoice
{
    public int Id { get; set; }

    public User Sender { get; set; }

    public User Recipient { get; set; }

    public string? Description { get; set; }

    public DateTime Date{ get; set; }

    public float Amount { get; set; }
}

and add the DbSet to the context

...
public DbSet<Invoice> Invoices{ get; set; } = null!;
...

This time i add-migration and update-database but it gives me an error:

The introduction of the FOREIGN KEY constraint 'FK_Invoices_Users_SenderUsername' in the 'Invoices' table can result in the creation of loops or more propagation paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION or change the other FOREIGN KEY constraints.

And i cant quite figure out why it wasnt giving me the same error for the messages, I want the message to delete on cascade if the user is deleted and that works fine but as soon as i try to do the same thing with the invoices it gives me this error. I dont want to add OnDelete No action since i want the invoices to get deleted on user deletion too.

0 Answers
Related