I am using Entity Framework 4.3 Code First and I have a problem updating many-to-many relationships.
I have defined the following classes:
public abstract class Entity { [Column(Order = 0)] [Key] public int Id { get; set; } [Timestamp] [Column(Order = 1)] public byte[] Version { get; set; } } public class Video : Entity { public string Title { get; set; } public string Description { get; set; } public TimeSpan Length { get; set; } public virtual ICollection<Coworker> Coworkers { get; set; } } public class Coworker : Entity { public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<Video> Videos { get; set; } }
When the database is created, the scheme looks right: There is also a table “Video”, “Colleagues” and “Video encoders”, without
I use the repository template in the N-Tier application to access the database, my Insert and Update method looks like this:
public T Insert(T entity) { //Creates database context. When it disposes, it calls context.SaveChanges() using (var session = new DatabaseSession()) { session.Context.Set<T>().Add(entity); } } public T Update(T entity) { //Creates database context. When it disposes, it calls context.SaveChanges() using (var session = new DatabaseSession()) { entity = session.Context.Set<T>().Attach(entity); session.Context.Entry(entity).State = EntityState.Modified; } return entity; }
When I update an object, I create an entity object from DTO, so use DbSet.Attach instead of selecting it and updating the properties one by one.
When I initialize the database, I add some test data:
- Create 3 Colleagues where I give the first and last name. (A, B, C)
- Create 3 videos where I set the name, description and length, and also set a few employees. The first video has A, B, the second has B, C and the third has A, C.
When I list the video from the code, I see that the Video.Coworkers collection is filled with good values, and when I query the reference table (VideoCoworkers) in SQL Server Management Studio, it also looks good.
My problem is when I update, for example, the name of the video, it works. But when I try to remove existing employees (B and C) from Video2 and try to add employee A, then the connection will not be updated. It also does not work when I am only trying to add a new employee or trying to delete him. I create an object that is used as a parameter of the Update () method, creating a new Video object with a new collection of Coworkers (which are selected from the database using the Find () method by identifier).
What is the correct way to update many-to-many relationships?