クライアントインターフェイスガイド > TDV用TIBCO ADO .NET 2020データプロバイダー > ADO.NET (LINQ)の使用 > LINQアップデート
 
LINQの更新
次のセクションでは、LINQを使用してTDVオブジェクトを更新するいくつかの方法を示します。
LINQを使用したTDVオブジェクトのエンティティへの更新
次の例では、LINQクエリ構文を使用して更新するオブジェクトを取得してから、オブジェクトのプロパティを更新します。更新は、WHERE句のIDで選択された、一度に1つのレコードでのみ機能することに注意してください。
 
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);
}
LINQ要素演算子の使用
SingleOrDefaultおよびFirstOrDefault要素演算子は、操作するオブジェクトを取得するための代替方法を提供します。これらの要素演算子を使用して、複数のレコードの更新を簡素化することもできます。
更新する単一のエンティティの選択
前のLINQクエリと同じ結果を達成する別の方法は、次の例に示すように、SingleOrDefault要素演算子を使用することです。
 
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();
 
一連のエンティティの更新
複数のクエリを実行して、エンティティのセットを更新できます。次の例は、前の例に基づいてレコードのセット全体を更新し、更新ごとに1つのレコードというLINQによって課せられる制限を回避します。最初のクエリは、条件に一致する一連のレコード(この場合、ProductNameが「昆布」であるすべてのレコード)を取得します。
次に、IDごとに個別のクエリが実行され、その説明が変更されて保存されます。このアプローチのパフォーマンスの低下に注意してください。必要な更新ごとに個別の接続を確立する必要があります。
 
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);
}
}