Search code examples
c#entity-frameworkmany-to-many

Delete junction table record in Entity Framework Code First (M:M)


How do I delete a record in a junction table within Entity Framework 5?

When reverse engineering my DataContext, Entity Framework seems to have recognized my junction table and automatically added Collections to my Models to represent the M:M relationship. This is great when adding items, as I can simply build my entire Entity and everything gets inserted properly. Perfect.

However, I'm stumped on removing a relationship. For example, an Activity can have multiple Contacts associated to it, and this is linked using a junction table (dbo.ActivityContacts) that consists of the columns:

  • ActivityID
  • ContactID

Both my Activity and Contact models have been updated by EF with Collections to represent the other. For example, my Activity model looks like this:

    public class Activity
    {
        public int ActivityID { get; set; }
        public string Subject { get; set; }
        public virtual ICollection<Contacts> Contacts { get; set; }
    }

In a non-EF environment, I would simply delete the record from the junction table and move on with my day. However, it seems I cannot access the junction table directly using EF, so I'm a tad confused on how to remove the record (relationship).

How can I properly remove a record from a junction table in Entity Framework?


Solution

  • Agree with @Chris.

    Another solution is to do:

    context.Entry(activity).State = EntityState.Deleted;