我怎么能告诉NHibernate的只保存更改的属性 [英] How I can tell NHibernate to save only changed properties

查看:107
本文介绍了我怎么能告诉NHibernate的只保存更改的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Person类映射到数据库与NHibernate。 我从数据库加载对象,并将其发送给不同的客户。 第一个客户端将修改名称和国家属性。 第二个客户端将只修改名称属性。 然后两个返回修改的对象服务器。 当我从保存的第一个客户数据 - 然后正确保存,两个 - 姓名和国家更新。 当我挽救第二个客户端的数据 - 我有问题。这是从第一个客户端覆盖数据并保存新的名字和国家的初始值。

I have class Person mapped to database with NHibernate. I load objects from DB and send it to different clients. First client will modify Name and Country property. Second client will modify only Name property. Then both returns modified objects to server. When I save data from first client - then saved correctly, both - name and country updated. When I save data from second client - I have problem. It was override data from first client and save new name and initial value of country.

我怎么能告诉NHibernate的只保存名称值,而不是覆盖乡村的价值?

How I can tell NHibernate to save only Name value and not override Country value?

public class Person
{
    public string Name { get; set; }
    public string Country { get; set; }
}

public static List<Person> GetEntities()
{
    var factory = CreateSessionFactory();
    using (ISession session = factory.OpenSession())
    {
        return session.CreateCriteria<Person>().List<Person>();                
    }
}

public static void SaveEntities(List<Person> entities)
{
    var factory = CreateSessionFactory();
    using (ISession session = factory.OpenSession())
    {
         using (var t = session.BeginTransaction())
         {
             foreach (var person in entities)
             {
                 session.Merge(person);
             }

             t.Commit();
        }
    }
}

P.S:对不起,我英文不好

P.S: Sorry for my bad english

推荐答案

答案是:你不能。 NH不知道,只是名称变了。

The answer is: you can't. NH doesn't know that only the name changed.

您可以通过不允许并发编辑避免。例如由NH的乐观锁机制。第二个客户端将得到一个 StaleObjectStateException

You can avoid it by not allowing concurrent editing. For instance by NH's optimistic locking mechanism. The second client would get an StaleObjectStateException.

如果两个客户端的编辑实际上不是在同一时间(但都基于同一对象的状态),则需要确保所述第二客户端获取编辑之前的第一变化。例如通过前打开编辑器或通过从服务器发送一个改变的通知检索的实际状态。

If the editing of the two clients is actually not at the same time (but both based on the same object state), you need to make sure that the second client gets the changes of the first before editing. For instance by retrieving the actual state before opening the editor or by sending a changed notification from the server.

如果你想保持同步编辑,有相当一些工作要做。客户需要提供究竟发生了变化的信息。然后你只需要复制这些值。这是艰苦的工作。然后,你可能仍然有问题,即让合并后的值不适合。

If you want to keep the concurrent editing, you have quite some work to do. The client needs to provide the information what actually had changed. Then you need to copy only these values. This is hard work. Then you may still have the problem that the so merged values don't fit.

这篇关于我怎么能告诉NHibernate的只保存更改的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆