user2130865
user2130865

Reputation:

Entity Framework cascading delete

I have big problems with cascading deletes in Entity Framework 6. I have a simple database with just 2 tables, persons and addresses, each person can have 0 or many addresses -> 1:n relationship.

When I delete a person all addresses are also deleted -> GREAT!

But when I try to delete all addresses of a person I get an exception:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

I have searched the internet for the last 2 days and the only thing I found that should work was to create a combined primary key, but this also does not work for me.

I have written a short demo http://1drv.ms/1uKQTiR that demonstrates whats going on. Maybe anyone can have a look at it and give me some good advice!

Here is the code:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public List<Address> Addresses { get; set; }

    public Person()
    {
        Addresses = new List<Address>();
    }
}

public class Address
{
    public int Id { get; set; }
    public string City { get; set; }

    public Person Person { get; set; }

    public Address()
    {
    }
}

 public class Context:DbContext
{
    public DbSet<Person> Persons    { get; set; }
    public DbSet<Address> Addresses { get; set; }

    public Context(): base(@"server=.\SQLEXPRESS;Database=Pers;Trusted_Connection=True;")
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().HasMany(p => p.Addresses).WithRequired(p => p.Person).WillCascadeOnDelete(true);


        base.OnModelCreating(modelBuilder);
    }
}

Code to Delete:

        Person p = _ctx.Persons.Include(x => x.Addresses).FirstOrDefault();
        p.Addresses.Clear();
        _ctx.SaveChanges();

Upvotes: 1

Views: 750

Answers (1)

Maarten
Maarten

Reputation: 22955

If you use .Clear() or .Remove() you are orphaning the Address object, while not deleting it. And in your Address table you probably have a required column to store the person-id. The person-id is set to null or 0 and that is probably not a valid value.

You have to actually delete the adress. Your adress cannot exist without a person, and that is what you are trying to force when you use .Clear() or .Remove() without deleteing the record.

Upvotes: 1

Related Questions