title: Entity Framework adding multiple related entities with single insert
body: <p>I have a GenericService Add method like so:-</p>
  
  <pre><code>    public bool Add(T entity, Expression&lt;Func&lt;T, bool&gt;&gt; filter = null)
      {
          try
          {
              _genericRepository.Add(entity, filter);
          }
          catch (Exception e)
          {
              return false;
          }
          return true;
      }
  </code></pre>
  
  <p>and a GenericRepository Add method like so:-</p>
  
  <pre><code>    public void Add(T entity, Expression&lt;Func&lt;T, bool&gt;&gt; filter = null)
      {
          var existing = Get&lt;T&gt;(filter);
          if (existing.Result != null) return;
          Context.Add(entity);
          Save();
      }
  </code></pre>
  
  <p>This is the call I am doing in the ProductsController:-</p>
  
  <pre><code>    [HttpPost]
      public IActionResult Create([FromBody] Product product)
      {
          if (product == null)
              return BadRequest();
  
          var result = _productsService.Add(product, m =&gt; m.Name == product.Name);
          if (result)
          {
              return CreatedAtRoute("GetProducts", new { id = product.Id }, product);
  
          }
          return BadRequest("Item not added");
      }
  </code></pre>
  
  <p>I am creating this by means of an integration test as follows :-</p>
  
  <pre><code>        testBrand = new Brand { Name = "testBrand" };
          testImage = new Image { Name = "testImage", Url = "/Brands/adidas_logo_test.png" };
          testBrand.Image = testImage;
  
          testCategory = new Category {Name = "testCategory"};
  
          testProduct = new Product
          {
              Category = testCategory,
              Name = "testProduct",
              Brand = testBrand,
              BrandId = testBrand.Id,
              CategoryId = testCategory.Id,
              Deal = false,
              Description = "testDescription",
              Discount = "50% Discount",
              Image = testImage,
              ImageId = testImage.Id,
              Price = new decimal(50.00),
              Stock = 5
          };
  
      [Test]
      public async Task Create_CreateAProduct_NewBrandNewCategoryNewImageProductsController()
      {
          //Arrange 
  
          //Act
          //create new image
          var requestImage = "api/Images/";
          var postResponseImage = await _client.PostAsJsonAsync(requestImage, testImage);
          var created = await postResponseImage.Content.ReadAsStringAsync();
          var createdImage = JsonConvert.DeserializeObject&lt;Image&gt;(created);
  
          //Act
          testBrand.Image = createdImage;
          testBrand.ImageId = createdImage.Id;
          testImage.Id = createdImage.Id;
  
          var postResponseProduct = await _client.PostAsJsonAsync(requestProduct, testProduct);
          var createdProduct = await postResponseProduct.Content.ReadAsStringAsync();
          var createdProductObj = JsonConvert.DeserializeObject&lt;Product&gt;(createdProduct);
  
          var getResponse = await _client.GetAsync(requestProduct + "Get/" + createdProductObj.Id);
          var fetched = await getResponse.Content.ReadAsStringAsync();
          var fetchedProduct = JsonConvert.DeserializeObject&lt;Product&gt;(fetched);
  
          // Assert
          Assert.IsTrue(postResponseProduct.IsSuccessStatusCode);
          Assert.IsTrue(getResponse.IsSuccessStatusCode);
  
          Assert.AreEqual(testProduct.Name, createdProductObj.Name);
          Assert.AreEqual(testProduct.Name, fetchedProduct.Name);
  
          Assert.AreNotEqual(Guid.Empty, createdProductObj.Id);
          Assert.AreEqual(createdProductObj.Id, fetchedProduct.Id);
      }
  </code></pre>
  
  <p>Everything works fine, until I try to insert an entity that has multiple related entities.  Let me give an example.</p>
  
  <p>Lets say I have a Product, which has an FK ImageId, a FK for BrandId, and a FK for CategoryId.  The Brands entity has already a FK ImageId for the Image entity.</p>
  
  <p>Now when I try to insert a new product, its inserting 2 images, one which comes with the Brand, and the image for the Product itself.  So in the Images Table, I get 2 entries, when I only want 1 new entry for the Product Image.  Also, this is causing a problem when I want to use an existing image for a new product.</p>
  
  <p>So I was thinking of creating a new Service/Repository for the Product to Inherit from the Generic Service/Repository, and add some more logic to it.  However is there a better way to do this?</p>
  
  <p>Thanks for your help and time</p>