Home >Database >Mysql Tutorial >Can LINQ Perform Direct SQL Updates Without Select Statements?
Direct Updates with LINQ: Bypassing Select Statements
When working with SQL, direct updates without select statements can be created using conditionals. With LINQ, the common pattern involves selecting entities, modifying them, and submitting changes.
However, what if you want to execute direct updates using LINQ and defer execution? Is it possible to avoid transmitting data to the client and have the SQL execute directly?
The answer is yes. LINQ-to-SQL can generate update statements without the need for a select statement. This can be achieved by attaching an object with key values to the context and modifying its properties.
For example:
Foo foo = new Foo { FooId = fooId }; // create obj and set keys context.Foos.Attach(foo); foo.Name = "test"; context.SubmitChanges();
By setting UpdateCheck="Never" for all properties in the Dbml file, a single update statement will be generated without selecting the original entity first.
One caveat to note is that if you want to set a property to null, you need to initialize the object with a different value to allow LINQ to detect the change. For instance:
Foo foo = new Foo { FooId = fooId, Name = "###" }; ... foo.Name = null;
Additionally, you can check for a timestamp during the update by setting the property to UpdateCheck="Always" in the Dbml file. This ensures that the update statement includes a condition based on the timestamp value.
The above is the detailed content of Can LINQ Perform Direct SQL Updates Without Select Statements?. For more information, please follow other related articles on the PHP Chinese website!