【问题标题】:LINQ update question comparing to SQL update. need helpLINQ 更新问题与 SQL 更新相比。需要帮忙
【发布时间】:2011-06-12 00:43:18
【问题描述】:

在下面的代码中,我使用 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 更新表达式?

我在这里不是在谈论性能。

【问题讨论】:

    标签: c# .net linq linq-to-sql linq-to-entities


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多