none
How to Save to a Many to Many tables using EF4.1 Code first RRS feed

  • Question

  • I have the following entities.

     

    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; }
    }
    
     public class EventConfiguration : EntityTypeConfiguration<Event> {
     public EventConfiguration () {
      ToTable("Events");
      HasKey(x => x.Id).Property(x => x.Id).HasColumnName("Id").IsRequired();
      Property(x => x.Name).HasColumnName("Name").IsRequired();
    
     HasMany(x => x.Tags)
      .WithMany(x => x.Events)
      .Map(m => {
       m.ToTable("EventTags");
       m.MapLeftKey("EventId");
       m.MapRightKey("TagId");
      });
     }
     }
    
    
    public class TagConfiguration : EntityTypeConfiguration<Tag> {
     public TagConfiguration () {
      ToTable("Tags");
      HasKey(x => x.Id).Property(x => x.Id).HasColumnName("Id").IsRequired();
      Property(x => x.Name).HasColumnName("Name").IsRequired();
     }
     }
    
    
    
    

     

     

    The problem am facing is, anytime I call events.Tags.Add(tag) and call Save changes on the context, it ends up creating a new tag info in the Tags table instead of just inserting the EventId and TagId into just the EventTags Table.

    Base on the data below how do I add an event and tag into the EventTags Table. Lets say I want to add Event with Id=2 and and tag with Id =1 to the EventTags table.

     

    These are the records in my many to many tables

    --------------

    Events Table

    --------------

    Id  Name

    1 Test1

    2 Test2

     

    --------------

    EventTags

    -------------

    EventId TagId

    1 2

     

    -------------

    Tags

    ------------

    Id Name

    1 MVC

    2 C#


    Thanks

    Friday, August 12, 2011 2:11 PM

Answers