1

I have the following entities (pocos using Entity Framework 5):

  • Company: Id, Name, Applications, etc.
  • Application: Id, Name, etc.

There's a many-to-many relationship between companies and applications.

Having a company (without the apllications relationship loaded from the database) and a collection of application ids, I would like to clear the applications from the company and add the applications with ids specified in the collection.

I can attach applications using their ids, without loading them from the database, like this:

foreach (int id in selectedApplications)
{
    Application application = new Application() { Id = id };
    _context.Applications.Attach(application);
    company.Applications.Add(application);
}
_context.SaveChanges();

But I need to clear the applications relationship first. Is there any way to clear a many-to-many relationship without loading it from the database first?

david.s
  • 10,853
  • 5
  • 48
  • 80

1 Answers1

1

This is only way. company.Applications must be loaded when you add or remove items from it, otherwise the change tracker will never be aware of any changes.

Also, the junction table is not an entity in the conceptual model, so there is no way to set primitive foreign key properties as is possible in foreign key associations. You have to access the associations by the object collections.

Community
  • 1
  • 1
Gert Arnold
  • 93,904
  • 24
  • 179
  • 256