Direct SQL Update with LINQ without Select
In LINQ, it is possible to generate SQL update commands without using a select statement, enabling direct updates on the database.
To achieve this, utilize the following approach:
Create an object and set its key properties:
Foo foo=new Foo { FooId=fooId };
Attach the object to the context:
context.Foos.Attach(foo);
Update object properties as needed:
foo.Name="test";
Submit changes to the database:
context.SubmitChanges();
By default, LINQ-to-SQL uses "UpdateCheck" to track changes in object properties. Setting it to "Never" for all properties ensures that LINQ will not perform any select queries to detect changes. Instead, it generates a direct update statement.
To update nullable properties, initialize the object with a non-null value for the property and then set it to null to trigger the update.
Additionally, to check for a timestamp during updates, set the "Modified" property to "UpdateCheck=Always" in the database model (dbml). This allows LINQ to verify whether the object has changed since the last retrieval.
The above is the detailed content of How to Perform Direct SQL Updates in LINQ without Using SELECT Statements?. For more information, please follow other related articles on the PHP Chinese website!