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 ?
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With