nHibernate返回不使用Id字段的单个对象(使用nHibernate 2.0)

时间:2010-08-12 12:03:22

标签: c# nhibernate

我想返回一个sngle对象,使用一个guid(它不是主键,但它是唯一的)

我可以使用id by:

返回单个对象
public User GetUserById(Int32 userId)
{
    User user = null;
    using (ITransaction tx = _session.BeginTransaction())
    {
        try
        {
            user = _session.Get<User>(userId);
            tx.Commit();
        } 
        catch (NHibernate.HibernateException) 
        {
            tx.Rollback();
           throw;
        }
    }
    return user;
}

但是想通过guid重新调整,但似乎无法这样做:

public User GetUserByGuId(Int32 guid) 
{
    User user = null;
    using (ITransaction tx = _session.BeginTransaction()) 
    {
        try 
        {
            user = _session.CreateQuery("select from User u where u.UserGuid =:guid")
                   .SetString("guid", guid)
                   .???? 
            tx.Commit();
        } 
        catch (NHibernate.HibernateException) 
        {
            tx.Rollback();
           throw;
        }
    }
    return user;
}

先谢谢你

1 个答案:

答案 0 :(得分:2)

UniqueResult&lt; T&gt;();

另外,使用 SetParameter()代替SetString()。

public User GetUserByGuId(Int32 guid) 
{
    User user = null;
    using (ITransaction tx = _session.BeginTransaction()) 
    {
        try 
        {
            user = _session.CreateQuery("from User u where u.UserGuid =:guid")
            .SetParameter("guid", guid)
            .UniqueResult<User>();
            tx.Commit();
        } 
        catch (NHibernate.HibernateException) 
        {
            tx.Rollback();
            throw;
        }
    }
    return user;
} 

使用NHibernate.Linq

user = session.Linq<User>().Where(u => u.UserGuid == guid).SingleOrDefault();