Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update in Linq an entity that is disconnected from database?

Tags:

c#

linq

Code below does not run correctly and throws InvalidOperationExcepiton.

public void Foo()
{
 DataContext context = new DataContext();
 LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
 context.LinqEntities.Attach(item, true);
}
like image 938
Ali Ersöz Avatar asked Sep 02 '08 17:09

Ali Ersöz


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.

Which entities can LINQ use to perform queries?

LINQ to Entities queries are comprised of LINQ standard query operators (such as Select, Where, and GroupBy) and expressions (x > 10, Contact. LastName, and so on). LINQ operators are not defined by a class, but rather are methods on a class.

Is LINQ to SQL still used?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.

Is LINQ to SQL an ORM?

LINQ to SQL is an object-relational mapping (ORM) implementation that allows the direct 1-1 mapping of a Microsoft SQL Server database to . NET classes, and query of the resulting objects using LINQ.


1 Answers

By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.

This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data.

Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values.

LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"}; 
context.LinqEntities.Attach(item);
item.Name = "John";
item.Surname = "Doe";
context.SubmitChanges();
like image 65
Scott Nichols Avatar answered Oct 23 '22 03:10

Scott Nichols