简体   繁体   中英

Updating Child Entities in Entity Framework not working

Hello I have a class called Property:

It has the following child entities:-

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; }

}

When I try updating Property and along with it the Child Entities, I see new records created for Child Entities instead of existing one's updated. For example I send ImageSortOrder in Property to be updated:-

           //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);

As you can see I am trying to update a child entity with Id 862. Instead it creates a new record with Id - 863.

My understanding is that it should update child entities if they are already present. Instead it seems to be adding new records.

Can anyone tell me what is going and how do I resolve the issue.

You're creating new instance of ImageSortOrder, and the Id value is assigned automatically by database. If you want to update existing object, you should get it from the DbContext and update it's properties.

Alternatively, you can use Attach method on the DbSet, instead Add on child collection. It will work like you expect.

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

    // Now you can update the properties...

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

yepp and here is why i hate EF. but your code should be like this.

If you want a better library that do just what you said try my library EntityWorker.Core

//Property Image

    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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM