2

わかりました、ループせずにデータベース内の複数の行を一度に更新したいとしましょう。ループを使用すると、次のようになります。

var products = (from prod in context.Products
               where prod.ProductCategoryID == myProductID
               select prod).ToList();


// modify each object
foreach (var product in products)
{
    product.PhoneNumber = ???;
    product.Name = ???;
    product.Address = ???;
}


context.SubmitChanges();

これを行うより良い方法はありますか?ループを行わずに?私はlinqの初心者だと考えてください。より良い方法があれば、例を挙げていただければ幸いです。よろしくお願いします。

4

2 に答える 2

2

LINQレコードのクエリ用です。現在のforeachループはより読みやすく、他のアプローチを試すと、内部でループが使用されます。

LINQ を使用してコレクションを変更するこの回答を見ることができますが、これは推奨される方法ではありません。

于 2013-05-21T06:49:03.270 に答える
0

You can use that line:

var products = (from prod in context.Products
                where prod.ProductCategoryID == myProductID
                select new Product(prod.PhoneNumber.ToLower(), prod.Name.ToUpper(), prod.Address.Trim()).ToList();

If you wanna change your products directly in your context object : make a specific function in Products class only. It will simply well designed.

 (from prod in context.Products
  where prod.ProductCategoryID == myProductID
  select prod.MakeChange(myPhoneNumber, myName, myAddress);

As you can call that line of code, prod should be changed along the LINQ query.

于 2013-05-21T06:58:46.297 に答える