5

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)

Joris Brauns
  • 263
  • 1
  • 3
  • 17
  • Are you calling `SaveChanges()`? – Sam Leach Mar 13 '14 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? – D Stanley Mar 13 '14 at 14:38
  • Please post the code that (supposedly) deletes the records from the db using EF. – Sam Leach Mar 13 '14 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) – Joris Brauns Mar 14 '14 at 09: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. – DanS Mar 14 '14 at 13:38
  • Yeah, thats what i'm doing now (removing directly from the context) i was hoping it could been done automaticly while removing it from the collection. – Joris Brauns Mar 15 '14 at 14:17

1 Answers1

12

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.

Community
  • 1
  • 1
DanS
  • 792
  • 5
  • 10