我想返回一个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;
}
先谢谢你
答案 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;
}
user = session.Linq<User>().Where(u => u.UserGuid == guid).SingleOrDefault();