gpt4 book ai didi

c# - 与 SQL 更新相比的 LINQ 更新问题。需要帮忙

转载 作者:行者123 更新时间:2023-11-30 18:41:49 24 4
gpt4 key购买 nike

在下面的代码中,我使用 TryUpdateModel 按 Id 更新 IndexOrder。以下更新命中 DB 2 次。一旦通过 Id 检索当前记录而不是更新单行。

我正在使用 LINQ To EF

 foreach (var i in indexArraay)
{
SubMenu existingMenu = _menu.SubSingle(Int32.Parse(i.id.ToString()));
existingMenu.IndexOrder = string.IsNullOrEmpty(i.index.ToString()) ? 0 : Int32.Parse(i.index.ToString());
TryUpdateModel(existingMenu);
_menu.Add();
}

在 SQL 中,我们不会像下面的语句那样这样做。

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

是我哪里错了还是有更好的方法来编写 LINQ 更新表达式?

我不是在这里谈论性能。

最佳答案

在 LINQ-to-SQL 中,您可以为此使用 Attach。下面的代码将更新 ID 为 1 的现有菜单项的 Order 值。

int myId = 1;
int newOrder = 10;

using (var dataContext = new DataContext("..."))
{
var table = dataContext.GetTable(typeof(Type));
var menuItem = new MenuItem { Id = myId };
table.Attach(menuItem);
menuItem.Order = newOrder;
dataContext.SubmitChanges();
}

[编辑]

对于 LINQ-to-Entities,请查看 Attaching and Detaching Objects .

模拟是ObjectSet.Attach Method .

关于c# - 与 SQL 更新相比的 LINQ 更新问题。需要帮忙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6319423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com