3

不确定我是否在这里遗漏了什么。基本上,我正在寻找 Linq to Nhibernate 来执行以下 SQL 语句:

update SomeTable
set SomeInteger = (SomeInteger + 1)
where SomeInteger > @NotSoMagicNumber

有没有办法做到这一点?

谢谢!

4

3 回答 3

5

迟到的答案,但它现在存在于 Nhibernate 5.0 中。

    //
    // Summary:
    //     Update all entities selected by the specified query. The update operation is
    //     performed in the database without reading the entities out of it.
    //
    // Parameters:
    //   source:
    //     The query matching the entities to update.
    //
    //   expression:
    //     The update setters expressed as a member initialization of updated entities,
    //     e.g. x => new Dog { Name = x.Name, Age = x.Age + 5 }. Unset members are ignored
    //     and left untouched.
    //
    // Type parameters:
    //   TSource:
    //     The type of the elements of source.
    //
    // Returns:
    //     The number of updated entities.
    public static int Update<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, TSource>> expression);

在你的情况下:

    session.Query<SomeObject>()
            .Update(i => new SomeObject { SomeInteger = i.SomeInteger + 1 });

感谢 NHibernate 团队!

于 2017-11-01T11:37:31.503 回答
1

与大多数(如果不是全部)LINQ 提供程序一样,LINQ to NHibernate 仅在读取数据时有用。

为了在 LINQ 的帮助下在 NHibernate 中实现您想要做的事情,您需要获取所有相关对象并更新每个对象。就像是:

//NHibernate session initialisation & finalisation skipped for brevity

var relevantObjects = from i in session.Linq<SomeObject>()
                      where i.SomeInteger > notSoMagicNumber
                      select i;

foreach (SomeObject item in relevantObjects)
{
    i.SomeInteger++;
    session.Update(item);
}

确保在所有这些之后刷新会话,并将其全部包装在事务中以最小化数据库更新的数量。

综上所述,根据数据的大小,您可能会在使用 NHibernate 进行批量操作时遇到性能问题。为此目的使用 anIStatelessSession可能会有所帮助,但我自己还没有尝试过。

UPDATE事实证明,如果您将其包装在事务中,则无需执行session.Update或刷新会话。

于 2010-01-30T09:12:27.677 回答
1

Linq(不是 Linq to NHibernate,一般是 Linq)没有 SQL 那样的批量更新动词。如果您需要像您这样的批量更新语句的效率,我会坚持使用 SQL。

于 2010-02-05T08:11:37.697 回答