[英]Entity Framework - Updating entity with added/modified child and grandchild entities
[英]Updating Child Entities in Entity Framework not working
您好,我有一個叫做Property的類:
它具有以下子實體:
Public class Property
{
public virtual ICollection<PropertyUrl> Property_URLs { get; set; }
public virtual ICollection<BrochureData> Property_Brochures { get; set; }
public virtual ICollection<ImageSortOrder> Property_ImageSortOrders { get; set; }
}
當我嘗試更新Property及其子實體時,會看到為子實體創建的新記錄,而不是現有實體的已更新記錄。 例如,我在屬性中發送ImageSortOrder進行更新:-
//Property Image
ImageSortOrder imageSortOrder = new ImageSortOrder();
imageSortOrder.FileName = "Sai Test Image.jpg";
imageSortOrder.SortOrder = 2; ;
imageSortOrder.Image_Cloudinary_PublicId = "Test_1234";
imageSortOrder.Image_Cloudinary_Url = "www.jll.com";
imageSortOrder.MimeType = "jpg";
imageSortOrder.IsActive = true;
imageSortOrder.ModifiedOn = DateTime.Now;
imageSortOrder.SortOrder = 1;
imageSortOrder.ImageSortOrderId = 862;
p.Property_ImageSortOrders.Add(imageSortOrder);
如您所見,我正在嘗試使用ID 862更新子實體。相反,它使用ID-863創建了一條新記錄。
我的理解是,如果子實體已經存在,它應該更新它們。 相反,它似乎正在添加新記錄。
誰能告訴我怎么回事以及如何解決該問題。
您正在創建ImageSortOrder的新實例,並且數據庫自動分配了ID值。 如果要更新現有對象,則應從DbContext中獲取它並更新其屬性。
或者,您可以在DbSet上使用Attach方法,而不是在子集合上添加。 它會像您期望的那樣工作。
var entity = new ImageSortOrder{ ImageSortOrderId = 862};
db.ImageSortOrders.Attach(entity);
// Now you can update the properties...
// ...and save changes
db.SaveChanges();
是的,這就是為什么我討厭英孚。 但是您的代碼應該是這樣的。
如果您想要一個更好的庫來滿足您的要求,請嘗試我的庫EntityWorker.Core
//屬性圖片
ImageSortOrder imageSortOrder = dbcontext.Property_ImageSortOrders.Where(c=> c.ImageSortOrderId == 862).First();
imageSortOrder.FileName = "Sai Test Image.jpg";
imageSortOrder.SortOrder = 2; ;
imageSortOrder.Image_Cloudinary_PublicId = "Test_1234";
imageSortOrder.Image_Cloudinary_Url = "www.jll.com";
imageSortOrder.MimeType = "jpg";
imageSortOrder.IsActive = true;
imageSortOrder.ModifiedOn = DateTime.Now;
imageSortOrder.SortOrder = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.