【问题标题】:NHibernate: explicit update-call on attached entityNHibernate:对附加实体的显式更新调用
【发布时间】:2011-03-06 16:50:25
【问题描述】:

虽然我使用 NHibernate 已经有一段时间了,但我仍然对这个 ORM 的一些基本概念有误解。假设我有一个名为“Blog”的类,我像这样加载一个持久化实例:

using (var tx = Session.BeginTransaction())
{
    var myBlog = Session.Get(10);

    tx.Commit();
}

如果我现在更改此实例的属性,NHibernate 似乎会自动检测未保存的更改,并将在事务提交时生成更新。

这导致以下语句完全相同:

using (var tx = Session.BeginTransaction())
{
    var myBlog = Session.Get(10);
    myBlog.Title = "Changed title";

    tx.Commit();
}

using (var tx = Session.BeginTransaction())
{
    var myBlog = Session.Get(10);

    myBlog.Title = "Changed title";
    Session.Update(myBlog); // why is this necessary?

    tx.Commit();
}

我看不出与 NHProf 有什么不同。那么为什么存在显式更新方法,我应该在什么时候使用它呢?

【问题讨论】:

    标签: nhibernate


    【解决方案1】:

    实体并不总是与会话连接。例如,您可以拥有带有方法的 web 服务,它接受一些实体,并在 db 中更新:

    [WebMethod]
    void UpdatePerson(int id, string name){
        using (var tx = Session.BeginTransaction(){
            var person = new Person(id, name);
            Session.Update(person);
            tx.Commit();
        }
    }
    

    此代码在数据库中执行更新而不发出选择。

    【讨论】:

    • 哇!这似乎对我当前的应用程序有很大的性能优势。对于我当前的更新方法,我总是先使用 id 来获取附加的实体,然后从我的 DTO 中一个一个地复制所有属性。这当然会导致 2 次 db-roundtrips,因为我必须在更新之前先获取实体!谢谢你的提示!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多