【问题标题】:Updating Child Entities in Entity Framework not working在实体框架中更新子实体不起作用
【发布时间】:2019-01-18 05:02:13
【问题描述】:

您好,我有一个名为 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; }

}

当我尝试更新属性以及子实体时,我看到为子实体创建了新记录,而不是更新了现有记录。例如,我在要更新的属性中发送 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 的新记录。

我的理解是,如果子实体已经存在,它应该更新它们。相反,它似乎在添加新记录。

谁能告诉我发生了什么以及如何解决这个问题。

【问题讨论】:

  • 当您将 ID 分配给您的对象时,如果您确定知道它存在。您可以通过调用 context.Entry(existingBlog).State = EntityState.Modified; 将该对象添加到 EF,这样 EF 会发现这是一个现有实体,需要对其进行更新。

标签: c# entity-framework


【解决方案1】:

您正在创建 ImageSortOrder 的新实例,并且 Id 值由数据库自动分配。如果你想更新现有对象,你应该从 DbContext 中获取它并更新它的属性。

或者,您可以在 DbSet 上使用 Attach 方法,而不是在子集合上使用 Add。它会像你期望的那样工作。

    var entity = new ImageSortOrder{ ImageSortOrderId = 862};
    db.ImageSortOrders.Attach(entity);

    // Now you can update the properties...

    // ...and save changes
    db.SaveChanges();

【讨论】:

  • 是的,这会起作用,但是当你在课堂上有孩子时,它就不起作用了,我已经用 herarkie 保存方法尝试了实体框架。
【解决方案2】:

是的,这就是我讨厌 EF 的原因。 但是你的代码应该是这样的。

如果你想要一个更好的库来做你所说的尝试我的库 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;

【讨论】:

  • 实际上不需要从数据库中获取实体,看我的回答。
猜你喜欢
  • 1970-01-01
  • 2014-09-07
  • 2011-06-11
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 2015-12-20
相关资源
最近更新 更多