0

I am new with EF Code First and have some troubles with it.

Here my Model

public class User 
{
    public string Id { get; set; }
    public string Name { get; set; }
    public virtual Address Address { get; set; }
}

public class Address 
{
    public string Id { get; set; }
    public string Street { get; set; }
    public string Nr { get; set; }
}

What I want is, if I write the following code:

user.Address = null; 

the related Address (record in database) should be deleted, but it is not! It removes only the foreign key in Users table. Also when I assign a new Address:

user.Address = new Address() { ... }; 

it is created a second record in database, why?

I want:

  1. if assign null to user.Address the database record should be deleted

  2. if assign a new Address object to user.Address it should replace the existing records data with the new one

How can I solve this?

0

1 Answer 1

1

If you need to delete an entity you need to mark it as deleted. Setting a navigation property to null will not delete the related entity. Note that there may be many navigation properties (different entities) pointing to the related entity and they all would be affected in the scenario you are describing. Because you create a new Address a new entity is created. Then you set your navigation property to a newly created property this breaks the old relationship and creates a new one. Since the entity you created is not in the database it will be added. You also did not delete the old entity so it was not deleted from the database. If you just want to change property values of an entity just set properties to new values and invoke SaveChanges. This should update data in the database.

2
  • thanks pawel, you are correct but I would like to narrow down my model further. user and address should stay in one-to-one relationship, in which address can not exist without a user. So it must be possible that Address is deleted when user.Address is set to NULL. Also Address should be deleted when the associated user is deleted (cascading). Any ideas how i can realize that or is that not possible with EF Code First? Oct 14, 2012 at 21:05
  • You probably could overwrite SaveChanges() to mark related entities as deleted if the navigation property was set to null. Deleting the address entity if the corresponding user is deleted should be possible just by setting up cascade delete
    – Pawel
    Oct 14, 2012 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.