Client Interfaces Guide > TIBCO ADO.NET 2020 Data Provider for TDV > Using ADO.NET (LINQ) > LINQ Updates
 
LINQ Updates
The following sections show several ways to update TDV objects with LINQ.
Updating TDV Objects with LINQ to Entities
The following example uses LINQ query syntax to obtain the object to be updated, then updates the object's properties. Note that updates only work on one record at a time, selected by its Id in the WHERE clause.
 
using System.Linq;
CompositeEntities context = new CompositeEntities();
var ProductsQuery = from Products in context.Products
where Products.Id == "22"
select Products;
foreach (var result in ProductsQuery) {
result.ProductName = "Konbu";
}
try {
context.SaveChanges();
} catch (Exception e) {
Console.WriteLine(e);
}
Using LINQ Element Operators
The SingleOrDefault and FirstOrDefault element operators provide alternative ways to obtain an object you want to manipulate. You can also use these element operators to simplify updating multiple records.
Selecting a Single Entity to Update
Another way to accomplish the same result as the preceding LINQ query is to use the SingleOrDefault element operator, as shown in the following example:
 
CompositeEntities context = new CompositeEntities();
var Products = context.Products.SingleOrDefault(o => o.Id == "150000-933272658");
Products.ProductName = "Ikura";
context.Entry(Products).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
 
Updating a Set of Entities
You can update a set of entities by performing multiple queries. The next example builds on the previous example to update an entire set of records and work around the limitation imposed by LINQ of one record per update. Our initial query retrieves a set of records that match the condition (in this instance, all the records whose ProductName is "Konbu").
Separate queries are then performed for each Id, whose descriptions are then changed and saved. Note the performance penalty for this approach; a separate connection must be established for each desired update.
 
CompositeEntities context = new CompositeEntities();
//Select everything matching the condition
var ProductsQuery = from Products in context.Products
where Products.ProductName == "Konbu"
select Products;
foreach (var result in ProductsQuery) {
//For each record matching the condition, perform a separate
//command to update the attributes you desire to change.
var updateRecord = from Products in context.Products
where Products.Id == result.Id
select Products;
//Since the record was selected using the record's unique primary key, you can derive the updateRecord using the
//FirstOrDefault method.
updateRecord.FirstOrDefault().Description = "test desc";
try {
//Commit the changes to the database.
context.SaveChanges();
} catch (Exception e) {
Console.WriteLine(e);
}
}