how to update entity without first loading it

asp.net-core entity-framework-core

Question

I am using EF core 2.2 with an asp.net core 2. I have a typical crud application where the user updates some entity information, and then I have to first select the entity by id and then update all the properties and save the entity. this introduces an extra select query that I would rather avoid. I have read a solution to this for previous EF versions was to attach the modified entity to the dbContext, and manually mark the changed properties and then save it without having to fetch it first from the db. However, I can't find any answers with respect to EF core, and I am wondering how to best do this.

1
1
6/23/2019 8:23:06 AM

Accepted Answer

This should give you an idea (taken from EF6 documentation but think it will work the same for EF core)

var existingBlog = new Blog { BlogId = 1 };

using (var context = new BloggingContext())
{
    context.Blogs.Attach(existingBlog);

    // Make your changes...          

    context.SaveChanges();
}
0
6/23/2019 8:34:16 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow