EF - Fluent API - Many-To-Many - How to add relationship to existing record?












0















I want to create a many-to-many relationship with Fluent-API and to add entities to the database.



Here is my code so far:



class Program
{
static void Main(string args)
{
Bar bar = new Bar
{
Id = 1,
Street = "BarStreet"
};

Foo foo1 = new Foo
{

Name = "FooName1",
Bars = { bar },
};

Foo foo2 = new Foo
{
Name = "FooName2",
Bars = { bar },
};


using (SandBoxModelContext db = new SandBoxModelContext())
{
Bar existingBar = db.Bar.FirstOrDefault(b => b.Id == bar.Id);
if (existingBar != null)
{
foo1.Bars.ToList()[0] = existingBar;
foo1.Bars.ToList()[0] = existingBar;
}

db.Foo.Add(foo1);
db.Foo.Add(foo2);
db.SaveChanges();
}

Console.ReadLine();
}
}

class Foo
{
internal int Id { get; set; }
internal string Name { get; set; }

internal virtual ICollection<Bar> Bars { get; set; }

public Foo()
{
Bars = new HashSet<Bar>();
}
}

class Bar
{
internal int Id { get; set; }
internal string Street { get; set; }

internal virtual ICollection<Foo> Foos { get; set; }

public Bar()
{
Foos = new HashSet<Foo>();
}
}


When I first run the application everything works fine. I get two foos and one bar, which are related to each other through the joining table FooBar.



|    Foo    | |    Bar      | |  FooBar   |
|Id| Name | |Id| Street | |FooId|BarId|
|-----------| |-------------| |-----------|
| 1|FooName1| | 1|BarStreet1| | 1 | 1 |
| 2|FooName2| | 2 | 1 |


But the second time I get two additional foos, which is fine, but I get also a second bar-record.



|    Foo    | |    Bar      | |  FooBar   |
|Id| Name | |Id| Street | |FooId|BarId|
|-----------| |-------------| |-----------|
| 1|FooName1| | 1|BarStreet1| | 1 | 1 |
| 2|FooName2| | 2|BarStreet1| | 2 | 1 |
| 3|FooName1| | 3 | 2 |
| 4|FooName2| | 4 | 2 |


How can I add a relationship to an existing record?
In this case I want to add new Foos and connect them to an existing Bar-record.



Here my FluentApi-Configuration:



#region Foo
modelBuilder.Entity<Foo>()
.Property(f => f.Id)
.HasColumnType("int");
modelBuilder.Entity<Foo>()
.HasKey(f => f.Id);
modelBuilder.Entity<Foo>()
.Property(f => f.Name)
.HasColumnType("nvarchar(max)");
#endregion

//many-to-many configuration
modelBuilder.Entity<Foo>()
.HasMany(f => f.Bars)
.WithMany(b => b.Foos)
.Map(fb =>
{
fb.MapLeftKey("FooId");
fb.MapRightKey("BarId");
fb.ToTable("FooBar");
});


#region Bar
modelBuilder.Entity<Bar>()
.Property(f => f.Id)
.HasColumnType("int");
modelBuilder.Entity<Bar>()
.HasKey(f => f.Id);
modelBuilder.Entity<Bar>()
.Property(f => f.Street)
.HasColumnType("nvarchar(max)");
#endregion









share|improve this question





























    0















    I want to create a many-to-many relationship with Fluent-API and to add entities to the database.



    Here is my code so far:



    class Program
    {
    static void Main(string args)
    {
    Bar bar = new Bar
    {
    Id = 1,
    Street = "BarStreet"
    };

    Foo foo1 = new Foo
    {

    Name = "FooName1",
    Bars = { bar },
    };

    Foo foo2 = new Foo
    {
    Name = "FooName2",
    Bars = { bar },
    };


    using (SandBoxModelContext db = new SandBoxModelContext())
    {
    Bar existingBar = db.Bar.FirstOrDefault(b => b.Id == bar.Id);
    if (existingBar != null)
    {
    foo1.Bars.ToList()[0] = existingBar;
    foo1.Bars.ToList()[0] = existingBar;
    }

    db.Foo.Add(foo1);
    db.Foo.Add(foo2);
    db.SaveChanges();
    }

    Console.ReadLine();
    }
    }

    class Foo
    {
    internal int Id { get; set; }
    internal string Name { get; set; }

    internal virtual ICollection<Bar> Bars { get; set; }

    public Foo()
    {
    Bars = new HashSet<Bar>();
    }
    }

    class Bar
    {
    internal int Id { get; set; }
    internal string Street { get; set; }

    internal virtual ICollection<Foo> Foos { get; set; }

    public Bar()
    {
    Foos = new HashSet<Foo>();
    }
    }


    When I first run the application everything works fine. I get two foos and one bar, which are related to each other through the joining table FooBar.



    |    Foo    | |    Bar      | |  FooBar   |
    |Id| Name | |Id| Street | |FooId|BarId|
    |-----------| |-------------| |-----------|
    | 1|FooName1| | 1|BarStreet1| | 1 | 1 |
    | 2|FooName2| | 2 | 1 |


    But the second time I get two additional foos, which is fine, but I get also a second bar-record.



    |    Foo    | |    Bar      | |  FooBar   |
    |Id| Name | |Id| Street | |FooId|BarId|
    |-----------| |-------------| |-----------|
    | 1|FooName1| | 1|BarStreet1| | 1 | 1 |
    | 2|FooName2| | 2|BarStreet1| | 2 | 1 |
    | 3|FooName1| | 3 | 2 |
    | 4|FooName2| | 4 | 2 |


    How can I add a relationship to an existing record?
    In this case I want to add new Foos and connect them to an existing Bar-record.



    Here my FluentApi-Configuration:



    #region Foo
    modelBuilder.Entity<Foo>()
    .Property(f => f.Id)
    .HasColumnType("int");
    modelBuilder.Entity<Foo>()
    .HasKey(f => f.Id);
    modelBuilder.Entity<Foo>()
    .Property(f => f.Name)
    .HasColumnType("nvarchar(max)");
    #endregion

    //many-to-many configuration
    modelBuilder.Entity<Foo>()
    .HasMany(f => f.Bars)
    .WithMany(b => b.Foos)
    .Map(fb =>
    {
    fb.MapLeftKey("FooId");
    fb.MapRightKey("BarId");
    fb.ToTable("FooBar");
    });


    #region Bar
    modelBuilder.Entity<Bar>()
    .Property(f => f.Id)
    .HasColumnType("int");
    modelBuilder.Entity<Bar>()
    .HasKey(f => f.Id);
    modelBuilder.Entity<Bar>()
    .Property(f => f.Street)
    .HasColumnType("nvarchar(max)");
    #endregion









    share|improve this question



























      0












      0








      0








      I want to create a many-to-many relationship with Fluent-API and to add entities to the database.



      Here is my code so far:



      class Program
      {
      static void Main(string args)
      {
      Bar bar = new Bar
      {
      Id = 1,
      Street = "BarStreet"
      };

      Foo foo1 = new Foo
      {

      Name = "FooName1",
      Bars = { bar },
      };

      Foo foo2 = new Foo
      {
      Name = "FooName2",
      Bars = { bar },
      };


      using (SandBoxModelContext db = new SandBoxModelContext())
      {
      Bar existingBar = db.Bar.FirstOrDefault(b => b.Id == bar.Id);
      if (existingBar != null)
      {
      foo1.Bars.ToList()[0] = existingBar;
      foo1.Bars.ToList()[0] = existingBar;
      }

      db.Foo.Add(foo1);
      db.Foo.Add(foo2);
      db.SaveChanges();
      }

      Console.ReadLine();
      }
      }

      class Foo
      {
      internal int Id { get; set; }
      internal string Name { get; set; }

      internal virtual ICollection<Bar> Bars { get; set; }

      public Foo()
      {
      Bars = new HashSet<Bar>();
      }
      }

      class Bar
      {
      internal int Id { get; set; }
      internal string Street { get; set; }

      internal virtual ICollection<Foo> Foos { get; set; }

      public Bar()
      {
      Foos = new HashSet<Foo>();
      }
      }


      When I first run the application everything works fine. I get two foos and one bar, which are related to each other through the joining table FooBar.



      |    Foo    | |    Bar      | |  FooBar   |
      |Id| Name | |Id| Street | |FooId|BarId|
      |-----------| |-------------| |-----------|
      | 1|FooName1| | 1|BarStreet1| | 1 | 1 |
      | 2|FooName2| | 2 | 1 |


      But the second time I get two additional foos, which is fine, but I get also a second bar-record.



      |    Foo    | |    Bar      | |  FooBar   |
      |Id| Name | |Id| Street | |FooId|BarId|
      |-----------| |-------------| |-----------|
      | 1|FooName1| | 1|BarStreet1| | 1 | 1 |
      | 2|FooName2| | 2|BarStreet1| | 2 | 1 |
      | 3|FooName1| | 3 | 2 |
      | 4|FooName2| | 4 | 2 |


      How can I add a relationship to an existing record?
      In this case I want to add new Foos and connect them to an existing Bar-record.



      Here my FluentApi-Configuration:



      #region Foo
      modelBuilder.Entity<Foo>()
      .Property(f => f.Id)
      .HasColumnType("int");
      modelBuilder.Entity<Foo>()
      .HasKey(f => f.Id);
      modelBuilder.Entity<Foo>()
      .Property(f => f.Name)
      .HasColumnType("nvarchar(max)");
      #endregion

      //many-to-many configuration
      modelBuilder.Entity<Foo>()
      .HasMany(f => f.Bars)
      .WithMany(b => b.Foos)
      .Map(fb =>
      {
      fb.MapLeftKey("FooId");
      fb.MapRightKey("BarId");
      fb.ToTable("FooBar");
      });


      #region Bar
      modelBuilder.Entity<Bar>()
      .Property(f => f.Id)
      .HasColumnType("int");
      modelBuilder.Entity<Bar>()
      .HasKey(f => f.Id);
      modelBuilder.Entity<Bar>()
      .Property(f => f.Street)
      .HasColumnType("nvarchar(max)");
      #endregion









      share|improve this question
















      I want to create a many-to-many relationship with Fluent-API and to add entities to the database.



      Here is my code so far:



      class Program
      {
      static void Main(string args)
      {
      Bar bar = new Bar
      {
      Id = 1,
      Street = "BarStreet"
      };

      Foo foo1 = new Foo
      {

      Name = "FooName1",
      Bars = { bar },
      };

      Foo foo2 = new Foo
      {
      Name = "FooName2",
      Bars = { bar },
      };


      using (SandBoxModelContext db = new SandBoxModelContext())
      {
      Bar existingBar = db.Bar.FirstOrDefault(b => b.Id == bar.Id);
      if (existingBar != null)
      {
      foo1.Bars.ToList()[0] = existingBar;
      foo1.Bars.ToList()[0] = existingBar;
      }

      db.Foo.Add(foo1);
      db.Foo.Add(foo2);
      db.SaveChanges();
      }

      Console.ReadLine();
      }
      }

      class Foo
      {
      internal int Id { get; set; }
      internal string Name { get; set; }

      internal virtual ICollection<Bar> Bars { get; set; }

      public Foo()
      {
      Bars = new HashSet<Bar>();
      }
      }

      class Bar
      {
      internal int Id { get; set; }
      internal string Street { get; set; }

      internal virtual ICollection<Foo> Foos { get; set; }

      public Bar()
      {
      Foos = new HashSet<Foo>();
      }
      }


      When I first run the application everything works fine. I get two foos and one bar, which are related to each other through the joining table FooBar.



      |    Foo    | |    Bar      | |  FooBar   |
      |Id| Name | |Id| Street | |FooId|BarId|
      |-----------| |-------------| |-----------|
      | 1|FooName1| | 1|BarStreet1| | 1 | 1 |
      | 2|FooName2| | 2 | 1 |


      But the second time I get two additional foos, which is fine, but I get also a second bar-record.



      |    Foo    | |    Bar      | |  FooBar   |
      |Id| Name | |Id| Street | |FooId|BarId|
      |-----------| |-------------| |-----------|
      | 1|FooName1| | 1|BarStreet1| | 1 | 1 |
      | 2|FooName2| | 2|BarStreet1| | 2 | 1 |
      | 3|FooName1| | 3 | 2 |
      | 4|FooName2| | 4 | 2 |


      How can I add a relationship to an existing record?
      In this case I want to add new Foos and connect them to an existing Bar-record.



      Here my FluentApi-Configuration:



      #region Foo
      modelBuilder.Entity<Foo>()
      .Property(f => f.Id)
      .HasColumnType("int");
      modelBuilder.Entity<Foo>()
      .HasKey(f => f.Id);
      modelBuilder.Entity<Foo>()
      .Property(f => f.Name)
      .HasColumnType("nvarchar(max)");
      #endregion

      //many-to-many configuration
      modelBuilder.Entity<Foo>()
      .HasMany(f => f.Bars)
      .WithMany(b => b.Foos)
      .Map(fb =>
      {
      fb.MapLeftKey("FooId");
      fb.MapRightKey("BarId");
      fb.ToTable("FooBar");
      });


      #region Bar
      modelBuilder.Entity<Bar>()
      .Property(f => f.Id)
      .HasColumnType("int");
      modelBuilder.Entity<Bar>()
      .HasKey(f => f.Id);
      modelBuilder.Entity<Bar>()
      .Property(f => f.Street)
      .HasColumnType("nvarchar(max)");
      #endregion






      api reference static record fluent






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 30 '18 at 11:25







      H.C.

















      asked Dec 28 '18 at 12:46









      H.C.H.C.

      12




      12
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958855%2fef-fluent-api-many-to-many-how-to-add-relationship-to-existing-record%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958855%2fef-fluent-api-many-to-many-how-to-add-relationship-to-existing-record%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'