tags:

views:

44

answers:

1

I want to return a sngle object usig a guid (its not the primary key, but it is unique)

I am able to return a single object using the 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;
}

But want to retun by guid but cannot seem to do so:

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;
}

Thank you in advaced

+1  A: 

.UniqueResult < T >();

Also, use SetParameter() instead of 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;
} 

Using NHibernate.Linq:

user = session.Linq<User>().Where(u => u.UserGuid == guid).SingleOrDefault();
Rafael Belliard
Thank you So much