EF4 Code First - Many to many relationship issue

Posted by Yngve B. Nilsen on Stack Overflow See other posts from Stack Overflow or by Yngve B. Nilsen
Published on 2011-03-11T07:53:40Z Indexed on 2011/03/11 8:10 UTC
Read the original article Hit count: 283

Hi!

I'm having some trouble with my EF Code First model when saving a relation to a many to many relationship. My Models:

public class Event
{
    public int Id { get; set; }
    public string Name { get; set; }  
    public virtual ICollection<Tag> Tags { get; set; }
}


public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Event> Events { get; set; }
}

In my controller, I map one or many TagViewModels into type of Tag, and send it down to my servicelayer for persistence. At this time by inspecting the entities the Tag has both Id and Name (The Id is a hidden field, and the name is a textbox in my view)

The problem occurs when I now try to add the Tag to the Event. Let's take the following scenario:

The Event is already in my database, and let's say it already has the related tags C#, ASP.NET

If I now send the following list of tags to the servicelayer:

ID  Name
1   C#
2   ASP.NET
3   EF4

and add them by first fetching the Event from the DB, so that I have an actual Event from my DbContext, then I simply do

myEvent.Tags.Add

to add the tags.. Problem is that after SaveChanges() my DB now contains this set of tags:

ID  Name
1   C#
2   ASP.NET
3   EF4
4   C#
5   ASP.NET

This, even though my Tags that I save has it's ID set when I save it (although I didn't fetch it from the DB)

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc