4

我正在使用 Fluent NHibernate 进行 NHibernate 映射,但现在我遇到了一个不知道如何解决的问题。下面是问题的简化版本。

我有一个用户类:

public class User {
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

这是关联的 Fluent NHibernate 类映射

public class UserMap : ClassMap<User> {
    public UserMap() {
        Id(x => x.Id);
        Map(x => x.FirstName);
        Map(x => x.LastName);
    }
}

我有两个网络表单。一个表单允许我更改用户的名字,第二个表单允许我更改用户的姓氏。我想要实现的是一个简单的 SQL 语句,如下所示:

对于第一种形式:
UPDATE [users] SET firstname='new first name' WHERE id=1

对于第二种形式:
UPDATE [users] SET lastname='new last name' WHERE id=1

目前 NHibernate 在我的数据库上执行以下 SQL:
UPDATE [users] SET firstname=null, lastname='new last name' WHERE id=1

现实世界应用程序中的问题是,在某些大对象上更新的属性太多(以及访问限制),并且更新整个对象似乎毫无意义,而我想要/被允许做的只是更新单一属性。

我希望有人可以就我如何实现这一点提供一些建议,或者指出我解决这个问题的正确方向。

4

2 回答 2

0

Hibernate 的做法是正确的,但您的问题表明您的架构需要一些规范化。

于 2009-11-10T17:14:02.757 回答
0

Ok, that works, Thanks for the help and tips Queen3!

here is how I sovled it:

using (var sf = Repository.CreateSessionFactory()) { 
    using (var s = sf.OpenSession()) { 
        using (var t = session.BeginTransaction()) { 
            var existingUser = s.Get<User>(editedUser.Id); 
            existingUser.LastName = editedUser.LastName; 
            s.SaveOrUpdate(existingUser); 
            t.Commit(); 
        }
    } 
} 

Although this does work, it requires that I retrieve the User from the database first and work within the same session. The good thing is that the sql statement that is generated just updates the dirty LastName field. :-)

I am unable to get it to work with a detached instance of the user, this is similar to how I was doing it before, which resulted in every field of the user being updated.

using (var sf = Repository.CreateSessionFactory()) { 
    using (var s = sf.OpenSession()) { 
        using (var t = session.BeginTransaction()) { 
            s.SaveOrUpdate(editedUser); 
            t.Commit(); 
        }
    } 
}
于 2009-11-11T13:56:05.947 回答