Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a single row in linq

Tags:

c#

sql

linq

I'm trying to update a single row of a table, specifically using a primary key value using linq.

 var mytab = new Customer();
 mytab.FirstName = mymodel.FirstName;
 mytab.LastName = mymodel.LastName;
 mytab.CustomerId = mymodel.CustomerId;

 db.AddToCustomer(mytab);
 db.SaveChanges()

This adds a new row with a new id. Stepping through the code reveals that mymodel is passing the correct values with a first or last name that I want to update.

The mymodel.CustomerId is the correct id of the record I want to update but SQL Profiler shows I'm not updating anything. Do I need to use .First ?

like image 503
user2284341 Avatar asked Oct 08 '13 15:10

user2284341


People also ask

How do you update a record in LINQ?

To update a row in the databaseQuery the database for the row to be updated. Make desired changes to member values in the resulting LINQ to SQL object. Submit the changes to the database.

Is there something like LINQ in Java?

In . NET, an easy way for you to simplify querying datasets is LINQ. Java doesn't have this, but since the introduction of Java 8 in 2014, you do now have the possibility to use "streams". Both LINQ and streams are ways to simplify querying datasets and to provide developers with an easy API to use.

How do I delete a record in LINQ query?

You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands. LINQ to SQL does not support or recognize cascade-delete operations.


1 Answers

Your code creates new row. For updating you need first select your Customer by id from database and then update:

var mytab = db.Customers.First(g=>g.CustomerId == mymodel.CustomerId);
 mytab.FirstName = mymodel.FirstName;
 mytab.LastName = mymodel.LastName;
 db.SaveChanges();
like image 81
Andrey Gubal Avatar answered Oct 19 '22 22:10

Andrey Gubal