Converting sql query to linq/ entity framework

PratikShah111
PratikShah111 used Ask the Experts™
on
how to write a simple update query in linq.

Here is the sql statement for that

update tablex
set
username = variable1 where
id = variable2

how do we handle this in linq for Entity Framework
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Retired
Distinguished Expert 2017
Commented:
Hi PratikShah111;

The first thing to do is to instantiate the DbContext then retrieve the record from the database which you wish to modify something like this.
var result = (from rec in db.table
              where rec.id == variable2
              select rec).FirstOrDefault();

Open in new window

Then modify the fields in the record something like this.
result.username = variable1;

Open in new window

Then when you are ready save the changes.
db.SaveChanges();

Open in new window

Raja Jegan RSQL Server DBA & Architect, EE Solution Guide
Awarded 2009
Distinguished Expert 2018

Commented:
Above comment should help you out, anyhow this can be a good start to write your SELECT/INSERT/UPDATE/DELETE statements in LINQ..
https://www.c-sharpcorner.com/UploadFile/3d39b4/simple-select-insert-update-and-delete-using-linq-to-sql/
Fernando SotoRetired
Distinguished Expert 2017

Commented:
@Raja Jegan R; your post talks about Linq to SQL witch is not Entity Framework as the question is asking about.
Raja Jegan RSQL Server DBA & Architect, EE Solution Guide
Awarded 2009
Distinguished Expert 2018

Commented:
Sorry, thanks for correcting.. Just read the question again and I might have misunderstood earlier..
Fernando SotoRetired
Distinguished Expert 2017

Commented:
@Raja Jegan R; not a problem.  👍

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial