Riz
Riz

Reputation: 6676

how to update entity without first loading it

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.

Upvotes: 3

Views: 2323

Answers (1)

obaylis
obaylis

Reputation: 3034

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

Upvotes: 1

Related Questions