Note that there are some explanatory texts on larger screens.

plurals
  1. POSaving to a many to many relationship
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>I have the following entities.</p> <pre><code> public class Event { public int Id { get; set; } public string Name { get; set; } public virtual ICollection&lt;Tag&gt; Tags { get; set; } } public class Tag { public int Id { get; set; } public string Name { get; set; } public virtual ICollection&lt;Event&gt; Events { get; set; } } public class EventConfiguration : EntityTypeConfiguration&lt;Event&gt; { public EventConfiguration () { ToTable("Events"); HasKey(x =&gt; x.Id).Property(x =&gt; x.Id).HasColumnName("Id").IsRequired(); Property(x =&gt; x.Name).HasColumnName("Name").IsRequired(); HasMany(x =&gt; x.Tags) .WithMany(x =&gt; x.Events) .Map(m =&gt; { m.ToTable("EventTags"); m.MapLeftKey("EventId"); m.MapRightKey("TagId"); }); } } public class TagConfiguration : EntityTypeConfiguration&lt;Tag&gt; { public TagConfiguration () { ToTable("Tags"); HasKey(x =&gt; x.Id).Property(x =&gt; x.Id).HasColumnName("Id").IsRequired(); Property(x =&gt; x.Name).HasColumnName("Name").IsRequired(); } } /* 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# */ </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload