6

I have a model called 'target' retreived by entityframework with a collection addresses.

After removing all items that are not in excesting in another collection i'm saving my entity framework context.

However, when checking my database the records are still there. While my linq code made sure to remove the items from the collection.

Here is my linq code:

using (IUnitOfWork uow = _uow.CreateUnitOfWork())
{
    var target = _repository.GetByBron(uow, bron.BronId);
    target.Adressen.RemoveAll(x => source.Adressen.All(y => !y.Equals(x)));

    //Which calls Context.SaveChanges(); inside the unit of work class
    uow.Save(_logger);
}    

Update: The problem is not removing my record from the collection. Its when i'm calling the save on the context. The relation record in my database is still there... nothing has been deleted... aldo it was removed from the collection.

Solved I'm directly removing it from the context now. (with a seperated repository object)

6
  • Are you calling SaveChanges()? Commented Mar 13, 2014 at 14:33
  • What is the type of target.Adressen? Does RemoveAll just remove the items from the collection or is there something within that method that calls Remove on the underlying repository? Commented Mar 13, 2014 at 14:38
  • Please post the code that (supposedly) deletes the records from the db using EF. Commented Mar 13, 2014 at 14:58
  • I asumed that by removing the items from the collection and saving the context the records where deleted automaticly? There is nothing specific its just removing the items from collection. It does work when i'm adding items ... so why not by removing them? (updated my orginal post) Commented Mar 14, 2014 at 9:32
  • Its only going to delete the related record when the FK for the relationship is a part of the primary key of the related entity. But manually Removing/Deleting the entity from the context, directly, should remove them from the database. Commented Mar 14, 2014 at 13:38

1 Answer 1

13

This is very dependent upon the configuration of the relationships. See Entity Framework .Remove() vs. .DeleteObject()

Since your relationship sounds to be a many to many, you will likely need to call DeleteObject for the addresses themselves, as EF won't automatically delete the orphaned records.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.