Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities how to update a record

Okay, so I'm new to both EF and LINQ. I have figured out how to INSERT and DELETE but for some reason UPDATE seems to escape my grasp.

Here is a sample of my code:

EntityDB dataBase = new EntityDB(); Customer c = new Customer {      Name = "Test",      Gender = "Male }; dataBase.Customers.AddObject(c); dataBase.SaveChanges(); 

The above creates and adds a record just fine.

Customer c = (from x in dataBase.Customers              where x.Name == "Test"              selext x).First(); dataBase.Customers.DeleteObject(c); dataBase.SaveChanges(); 

The above effectively deletes the specified record.

Now how do I update? I can't seem to find an "UpdateObject()" method on the entity collection.

like image 761
Chev Avatar asked Jan 06 '11 17:01

Chev


People also ask

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

How do I update an existing record in Entity Framework?

We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.

Can we use LINQ with Entity Framework?

LINQ to Entities converts Language-Integrated Queries (LINQ) queries to command tree queries, executes the queries against the Entity Framework, and returns objects that can be used by both the Entity Framework and LINQ.


2 Answers

Just modify one of the returned entities:

Customer c = (from x in dataBase.Customers              where x.Name == "Test"              select x).First(); c.Name = "New Name"; dataBase.SaveChanges(); 

Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}

like image 145
tster Avatar answered Sep 18 '22 22:09

tster


//for update

(from x in dataBase.Customers          where x.Name == "Test"          select x).ToList().ForEach(xx => xx.Name="New Name"); 

//for delete

dataBase.Customers.RemoveAll(x=>x.Name=="Name"); 
like image 35
Zohaib Iqbal Avatar answered Sep 18 '22 22:09

Zohaib Iqbal