0

I have the following relationship defined, where both Customer and Retailer are foreign keys to a User. So a User can be either a Customer, Retailer or both. Each Customer can have a list of Retailers, and each Retailer can have a list of Customers.

The relationship is defined as:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Retailer>()
        .HasRequired(x => x.User);
    modelBuilder.Entity<Customer>() 
        .HasRequired(x => x.User);
}

with the entities defined as follows:

public class Retailer : Entity
{
    public string Name { get; set; }

    public virtual User User { get; set; }
    public ICollection<Customer> Customers { get; set; }
}

public class Customer : Entity
{
    public string Name { get; set; }

    public virtual User User { get; set; }
    public ICollection<Retailer> Retailers { get; set; }
}

public class User : AbpUser<Tenant, User>
{
    public string AccessToken { get; set; }
    public long UserId { get; set; }

    public virtual Retailer Retailer { get; set; }
    public virtual Customer Customer { get; set; }
}

When I try to delete a User that has a Customer or Retailer foreign key, I get the error (either depending on the type of foreign key):

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Customers_dbo.AbpUsers_User_Id". The conflict occurred in database "ShopDB", table "dbo.Customers", column 'User_Id'.

or

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Retailers_dbo.AbpUsers_User_Id". The conflict occurred in database "ShopDB", table "dbo.Retailers", column 'User_Id'.

What do I need to change so that when I delete a User all foreign referenes to the User are also cascade deleted?

DaveDev
  • 41,155
  • 72
  • 223
  • 385
  • Possible duplicate of [Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship](http://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations) – Eris Jun 16 '16 at 22:28
  • As Eris mentioned, have you tried using .WillCascadeOnDelete() after HasRequired? – smoksnes Jun 17 '16 at 05:06
  • Not a duplicate, because cascded delete will cause the infamous "multiple cascade paths" exception. But @DaveDev, the user doesn't have foreign keys here. Customer and Retailer have foreign keys to User. With your configuration I would rather expect that EF will try to nullify these foreign keys, and fails. You don't seem to have shown the correct (or full) mapping. – Gert Arnold Jun 18 '16 at 21:41

0 Answers0