2016-03-29 9 views
0

Bu şekilde bir Varlığı güncelleştirmeye çalıştım ancak Anahtarlar hakkında hatalar alıyorum.Bir Varlık ve çok fazla ilişki için birçok güncelleştirme nasıl yapılır

Öğe Ürününün parametrelerdeki veya yöntem içindeki ilişkilerini nasıl edinebilirim. Bence çözüm.

public static bool UpdateProduct(Product myProduct , int[] newCategoriesID) 
{ 
    bool operation = false; 
    using (var ctx = new TestContext()) 
    { 
     ctx.Entry(myProduct).State = EntityState.Modified; 
     var newCategories = ctx.Categories.Where(c => newCategoriesID.Contains(c.id)).ToList(); 
     myProduct.Categories.Clear(); 
     foreach (var newCat in newCategories) 
     { 
      myProduct.Categories.Add(newCat); 
     } 
     ctx.Products.Attach(myProduct); 
     int countChanges = ctx.SaveChanges(); 
     if (countChanges > 0) 
     { 
      operation = true; 
     } 
    } 
    return operation; 
} 

ASP.NET MVC 5 ve Entity Framework'ün son sürümünü kullanıyorum.

+0

ise bilmiyorum? –

+0

Değişiklikleri kaydetmeye çalıştığımda, veritabanındaki anahtarla ilgili bir sorun var. Hata: "PRIMARY KEY kısıtlaması '' PK_ProductCategory 'ihlali.' Dbo.ProductCategory 'nesne anahtarında yinelenen ekleyemezsiniz. Yinelenen anahtarın değeri (1004, 2)." Sanırım, benim parametremin Ben bir konsol uygulaması ile test ederken, örneğin "Ürün myproduct = ctx.Products.Include (" Kategoriler ") kullandığımda çalıştığından bu yana değil. SingleOrDefault (x => x.id == 1002); –

cevap

0

Bu çözüm çalışır ancak bu alıyorsanız hangi belirli hataları iyi

public static bool UpdateProduct(Product myProduct , int[] newCategoriesID) 
    { 
     bool operation = false; 
     using (var ctx = new TestContext()) 
     { 
//find the product in the database and include the relation 
      var existeproduct = ctx.Products.Include("Categories").SingleOrDefault(x=>x.id == myProduct.id); 
// Change the current and original values by copying the values from other objects 
      ctx.Entry(existeproduct).CurrentValues.SetValues(myProduct); 
      ctx.Entry(existeproduct).State = EntityState.Modified; 
      var newCategories = ctx.Categories.Where(c => newCategoriesID.Contains(c.id)).ToList(); 
      existeproduct.Categories.Clear(); 
      foreach (var newCat in newCategories) 
      { 
       existeproduct.Categories.Add(newCat); 
      } 
      int countChanges = ctx.SaveChanges(); 
      if (countChanges > 0) 
      { 
       operation = true; 
      } 
     } 
     return operation; 
    } 
İlgili konular