Entity Framework : When child entity is added, a duplicate parent entity is created instead of referencing...











up vote
0
down vote

favorite












enter image description here



A product can have multiple reviews. A review is made by a single customer.
Therefore, review has both Customer and Product as properties.



Product.cs



namespace DatabaseProject.Models
{
public class Product
{
public Product()
{
Reviews = new List < Review >();
}

public int Id { get; set; }
public Catagory Catagory { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public List<Review> Reviews { get; set; }
}
}


Review.cs



namespace DatabaseProject.Models
{
public class Review
{
public int Id { get; set; }
public string Text { get; set; }
public int Stars { get; set; }
[Required]
public Product Product { get; set; }
[Required]
public Customer Customer { get; set; }
}
}


Customer.cs



namespace DatabaseProject.Models
{
public class Customer
{
public Customer()
{
Addresses = new List<Address>();
Reviews = new List<Review>();
}

public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public List<Address> Addresses { get; set; }
public List<Review> Reviews { get; set; }
}
}


Method to add new review.



I add it to the reviews list in product table.



public bool AddReview(int id, Review review)
{
using (var context = new ShopDbContext())
{
Product oldProduct = context.Products.Find(id);
if (oldProduct == null)
{
return false;
}
oldProduct.Reviews.Add(review);


context.SaveChanges();
return true;
}
}


Adding a new Review



Here, since the review is added to product.Reviews I didn't have to pass the product property.



But I had to pass the customer. Somehow this creates a new customer rather than referencing the existing customer.



    productService.AddReview(1,
new Review
{
Customer = customerService.Get(1),
Stars = 2,
Text = "It's a good camera",
});


This causes a duplicate entry in Customers table.



enter image description here










share|improve this question




























    up vote
    0
    down vote

    favorite












    enter image description here



    A product can have multiple reviews. A review is made by a single customer.
    Therefore, review has both Customer and Product as properties.



    Product.cs



    namespace DatabaseProject.Models
    {
    public class Product
    {
    public Product()
    {
    Reviews = new List < Review >();
    }

    public int Id { get; set; }
    public Catagory Catagory { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Specification { get; set; }
    public List<Review> Reviews { get; set; }
    }
    }


    Review.cs



    namespace DatabaseProject.Models
    {
    public class Review
    {
    public int Id { get; set; }
    public string Text { get; set; }
    public int Stars { get; set; }
    [Required]
    public Product Product { get; set; }
    [Required]
    public Customer Customer { get; set; }
    }
    }


    Customer.cs



    namespace DatabaseProject.Models
    {
    public class Customer
    {
    public Customer()
    {
    Addresses = new List<Address>();
    Reviews = new List<Review>();
    }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public List<Address> Addresses { get; set; }
    public List<Review> Reviews { get; set; }
    }
    }


    Method to add new review.



    I add it to the reviews list in product table.



    public bool AddReview(int id, Review review)
    {
    using (var context = new ShopDbContext())
    {
    Product oldProduct = context.Products.Find(id);
    if (oldProduct == null)
    {
    return false;
    }
    oldProduct.Reviews.Add(review);


    context.SaveChanges();
    return true;
    }
    }


    Adding a new Review



    Here, since the review is added to product.Reviews I didn't have to pass the product property.



    But I had to pass the customer. Somehow this creates a new customer rather than referencing the existing customer.



        productService.AddReview(1,
    new Review
    {
    Customer = customerService.Get(1),
    Stars = 2,
    Text = "It's a good camera",
    });


    This causes a duplicate entry in Customers table.



    enter image description here










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      enter image description here



      A product can have multiple reviews. A review is made by a single customer.
      Therefore, review has both Customer and Product as properties.



      Product.cs



      namespace DatabaseProject.Models
      {
      public class Product
      {
      public Product()
      {
      Reviews = new List < Review >();
      }

      public int Id { get; set; }
      public Catagory Catagory { get; set; }
      public string Name { get; set; }
      public string Description { get; set; }
      public string Specification { get; set; }
      public List<Review> Reviews { get; set; }
      }
      }


      Review.cs



      namespace DatabaseProject.Models
      {
      public class Review
      {
      public int Id { get; set; }
      public string Text { get; set; }
      public int Stars { get; set; }
      [Required]
      public Product Product { get; set; }
      [Required]
      public Customer Customer { get; set; }
      }
      }


      Customer.cs



      namespace DatabaseProject.Models
      {
      public class Customer
      {
      public Customer()
      {
      Addresses = new List<Address>();
      Reviews = new List<Review>();
      }

      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Email { get; set; }
      public string Password { get; set; }
      public List<Address> Addresses { get; set; }
      public List<Review> Reviews { get; set; }
      }
      }


      Method to add new review.



      I add it to the reviews list in product table.



      public bool AddReview(int id, Review review)
      {
      using (var context = new ShopDbContext())
      {
      Product oldProduct = context.Products.Find(id);
      if (oldProduct == null)
      {
      return false;
      }
      oldProduct.Reviews.Add(review);


      context.SaveChanges();
      return true;
      }
      }


      Adding a new Review



      Here, since the review is added to product.Reviews I didn't have to pass the product property.



      But I had to pass the customer. Somehow this creates a new customer rather than referencing the existing customer.



          productService.AddReview(1,
      new Review
      {
      Customer = customerService.Get(1),
      Stars = 2,
      Text = "It's a good camera",
      });


      This causes a duplicate entry in Customers table.



      enter image description here










      share|improve this question















      enter image description here



      A product can have multiple reviews. A review is made by a single customer.
      Therefore, review has both Customer and Product as properties.



      Product.cs



      namespace DatabaseProject.Models
      {
      public class Product
      {
      public Product()
      {
      Reviews = new List < Review >();
      }

      public int Id { get; set; }
      public Catagory Catagory { get; set; }
      public string Name { get; set; }
      public string Description { get; set; }
      public string Specification { get; set; }
      public List<Review> Reviews { get; set; }
      }
      }


      Review.cs



      namespace DatabaseProject.Models
      {
      public class Review
      {
      public int Id { get; set; }
      public string Text { get; set; }
      public int Stars { get; set; }
      [Required]
      public Product Product { get; set; }
      [Required]
      public Customer Customer { get; set; }
      }
      }


      Customer.cs



      namespace DatabaseProject.Models
      {
      public class Customer
      {
      public Customer()
      {
      Addresses = new List<Address>();
      Reviews = new List<Review>();
      }

      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Email { get; set; }
      public string Password { get; set; }
      public List<Address> Addresses { get; set; }
      public List<Review> Reviews { get; set; }
      }
      }


      Method to add new review.



      I add it to the reviews list in product table.



      public bool AddReview(int id, Review review)
      {
      using (var context = new ShopDbContext())
      {
      Product oldProduct = context.Products.Find(id);
      if (oldProduct == null)
      {
      return false;
      }
      oldProduct.Reviews.Add(review);


      context.SaveChanges();
      return true;
      }
      }


      Adding a new Review



      Here, since the review is added to product.Reviews I didn't have to pass the product property.



      But I had to pass the customer. Somehow this creates a new customer rather than referencing the existing customer.



          productService.AddReview(1,
      new Review
      {
      Customer = customerService.Get(1),
      Stars = 2,
      Text = "It's a good camera",
      });


      This causes a duplicate entry in Customers table.



      enter image description here







      c# asp.net .net entity-framework entity-framework-6






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 10 at 14:13

























      asked Nov 10 at 13:52









      Enzio

      130110




      130110
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote













          I think you need a CustomerId propery in your Reviews table, and pass the customerId when adding a new review.



          public class Review
          {
          public int Id { get; set; }
          public string Text { get; set; }
          public int Stars { get; set; }
          [Required]
          public int ProductId { get; set; }
          [Required]
          public int CustomerId { get; set; }
          [ForeignKey("ProductId")]
          public Product Product { get; set; }
          [ForeignKey("CustomerId")]
          public Customer Customer { get; set; }
          }

          productService.AddReview(1,
          new Review
          {
          CustomerId = 1,
          ProductId = XXX,
          Stars = 2,
          Text = "It's a good camera",
          })


          Then, you would need to create a foreign key between ProductId and Product table, and CustomerId and Customer table.



          In this way, you wouldn't need to load the customer/product when addign a new review. You will only need the identifiers.






          share|improve this answer










          New contributor




          Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.

























            up vote
            0
            down vote













            Your Review Model should have a CustomerID & Review Model should look like this:



            namespace DatabaseProject.Models
            {
            public class Review
            {
            public int Id { get; set; }
            [Required]
            public int CustomerId { get; set; }
            [Required]
            public int ProductId { get; set; }
            public string Text { get; set; }
            public int Stars { get; set; }

            [ForeignKey("ProductId")]
            public Product Product { get; set; }

            [ForeignKey("CustomerId")]
            public Customer Customer { get; set; }
            }
            }


            And you must add a new review like this:



            productService.AddReview(1,
            new Review
            {
            CustomerId = 1,
            Stars = 2,
            Text = "It's a good camera",
            ProductId = 1
            })


            In present code you are passing an object of Customer Model in DbSet.Add method which adds a new entity to a context






            share|improve this answer























              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',
              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%2f53239648%2fentity-framework-when-child-entity-is-added-a-duplicate-parent-entity-is-crea%23new-answer', 'question_page');
              }
              );

              Post as a guest
































              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              1
              down vote













              I think you need a CustomerId propery in your Reviews table, and pass the customerId when adding a new review.



              public class Review
              {
              public int Id { get; set; }
              public string Text { get; set; }
              public int Stars { get; set; }
              [Required]
              public int ProductId { get; set; }
              [Required]
              public int CustomerId { get; set; }
              [ForeignKey("ProductId")]
              public Product Product { get; set; }
              [ForeignKey("CustomerId")]
              public Customer Customer { get; set; }
              }

              productService.AddReview(1,
              new Review
              {
              CustomerId = 1,
              ProductId = XXX,
              Stars = 2,
              Text = "It's a good camera",
              })


              Then, you would need to create a foreign key between ProductId and Product table, and CustomerId and Customer table.



              In this way, you wouldn't need to load the customer/product when addign a new review. You will only need the identifiers.






              share|improve this answer










              New contributor




              Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






















                up vote
                1
                down vote













                I think you need a CustomerId propery in your Reviews table, and pass the customerId when adding a new review.



                public class Review
                {
                public int Id { get; set; }
                public string Text { get; set; }
                public int Stars { get; set; }
                [Required]
                public int ProductId { get; set; }
                [Required]
                public int CustomerId { get; set; }
                [ForeignKey("ProductId")]
                public Product Product { get; set; }
                [ForeignKey("CustomerId")]
                public Customer Customer { get; set; }
                }

                productService.AddReview(1,
                new Review
                {
                CustomerId = 1,
                ProductId = XXX,
                Stars = 2,
                Text = "It's a good camera",
                })


                Then, you would need to create a foreign key between ProductId and Product table, and CustomerId and Customer table.



                In this way, you wouldn't need to load the customer/product when addign a new review. You will only need the identifiers.






                share|improve this answer










                New contributor




                Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.




















                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  I think you need a CustomerId propery in your Reviews table, and pass the customerId when adding a new review.



                  public class Review
                  {
                  public int Id { get; set; }
                  public string Text { get; set; }
                  public int Stars { get; set; }
                  [Required]
                  public int ProductId { get; set; }
                  [Required]
                  public int CustomerId { get; set; }
                  [ForeignKey("ProductId")]
                  public Product Product { get; set; }
                  [ForeignKey("CustomerId")]
                  public Customer Customer { get; set; }
                  }

                  productService.AddReview(1,
                  new Review
                  {
                  CustomerId = 1,
                  ProductId = XXX,
                  Stars = 2,
                  Text = "It's a good camera",
                  })


                  Then, you would need to create a foreign key between ProductId and Product table, and CustomerId and Customer table.



                  In this way, you wouldn't need to load the customer/product when addign a new review. You will only need the identifiers.






                  share|improve this answer










                  New contributor




                  Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  I think you need a CustomerId propery in your Reviews table, and pass the customerId when adding a new review.



                  public class Review
                  {
                  public int Id { get; set; }
                  public string Text { get; set; }
                  public int Stars { get; set; }
                  [Required]
                  public int ProductId { get; set; }
                  [Required]
                  public int CustomerId { get; set; }
                  [ForeignKey("ProductId")]
                  public Product Product { get; set; }
                  [ForeignKey("CustomerId")]
                  public Customer Customer { get; set; }
                  }

                  productService.AddReview(1,
                  new Review
                  {
                  CustomerId = 1,
                  ProductId = XXX,
                  Stars = 2,
                  Text = "It's a good camera",
                  })


                  Then, you would need to create a foreign key between ProductId and Product table, and CustomerId and Customer table.



                  In this way, you wouldn't need to load the customer/product when addign a new review. You will only need the identifiers.







                  share|improve this answer










                  New contributor




                  Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  share|improve this answer



                  share|improve this answer








                  edited Nov 10 at 14:36





















                  New contributor




                  Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  answered Nov 10 at 14:11









                  Gabitu

                  864




                  864




                  New contributor




                  Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  New contributor





                  Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






                  Gabitu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.
























                      up vote
                      0
                      down vote













                      Your Review Model should have a CustomerID & Review Model should look like this:



                      namespace DatabaseProject.Models
                      {
                      public class Review
                      {
                      public int Id { get; set; }
                      [Required]
                      public int CustomerId { get; set; }
                      [Required]
                      public int ProductId { get; set; }
                      public string Text { get; set; }
                      public int Stars { get; set; }

                      [ForeignKey("ProductId")]
                      public Product Product { get; set; }

                      [ForeignKey("CustomerId")]
                      public Customer Customer { get; set; }
                      }
                      }


                      And you must add a new review like this:



                      productService.AddReview(1,
                      new Review
                      {
                      CustomerId = 1,
                      Stars = 2,
                      Text = "It's a good camera",
                      ProductId = 1
                      })


                      In present code you are passing an object of Customer Model in DbSet.Add method which adds a new entity to a context






                      share|improve this answer



























                        up vote
                        0
                        down vote













                        Your Review Model should have a CustomerID & Review Model should look like this:



                        namespace DatabaseProject.Models
                        {
                        public class Review
                        {
                        public int Id { get; set; }
                        [Required]
                        public int CustomerId { get; set; }
                        [Required]
                        public int ProductId { get; set; }
                        public string Text { get; set; }
                        public int Stars { get; set; }

                        [ForeignKey("ProductId")]
                        public Product Product { get; set; }

                        [ForeignKey("CustomerId")]
                        public Customer Customer { get; set; }
                        }
                        }


                        And you must add a new review like this:



                        productService.AddReview(1,
                        new Review
                        {
                        CustomerId = 1,
                        Stars = 2,
                        Text = "It's a good camera",
                        ProductId = 1
                        })


                        In present code you are passing an object of Customer Model in DbSet.Add method which adds a new entity to a context






                        share|improve this answer

























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          Your Review Model should have a CustomerID & Review Model should look like this:



                          namespace DatabaseProject.Models
                          {
                          public class Review
                          {
                          public int Id { get; set; }
                          [Required]
                          public int CustomerId { get; set; }
                          [Required]
                          public int ProductId { get; set; }
                          public string Text { get; set; }
                          public int Stars { get; set; }

                          [ForeignKey("ProductId")]
                          public Product Product { get; set; }

                          [ForeignKey("CustomerId")]
                          public Customer Customer { get; set; }
                          }
                          }


                          And you must add a new review like this:



                          productService.AddReview(1,
                          new Review
                          {
                          CustomerId = 1,
                          Stars = 2,
                          Text = "It's a good camera",
                          ProductId = 1
                          })


                          In present code you are passing an object of Customer Model in DbSet.Add method which adds a new entity to a context






                          share|improve this answer














                          Your Review Model should have a CustomerID & Review Model should look like this:



                          namespace DatabaseProject.Models
                          {
                          public class Review
                          {
                          public int Id { get; set; }
                          [Required]
                          public int CustomerId { get; set; }
                          [Required]
                          public int ProductId { get; set; }
                          public string Text { get; set; }
                          public int Stars { get; set; }

                          [ForeignKey("ProductId")]
                          public Product Product { get; set; }

                          [ForeignKey("CustomerId")]
                          public Customer Customer { get; set; }
                          }
                          }


                          And you must add a new review like this:



                          productService.AddReview(1,
                          new Review
                          {
                          CustomerId = 1,
                          Stars = 2,
                          Text = "It's a good camera",
                          ProductId = 1
                          })


                          In present code you are passing an object of Customer Model in DbSet.Add method which adds a new entity to a context







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 10 at 14:41

























                          answered Nov 10 at 14:22









                          Muhammad Saqlain

                          2,19221934




                          2,19221934






























                               

                              draft saved


                              draft discarded



















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239648%2fentity-framework-when-child-entity-is-added-a-duplicate-parent-entity-is-crea%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest




















































































                              Popular posts from this blog

                              Florida Star v. B. J. F.

                              Danny Elfman

                              Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues