我正在考虑异步化一些现有代码。不幸的是,我缺乏NHibernate的经验。考虑到NHibernate 5对异步有很多支持,大多数NHibernate的东西都很容易。但是,我被困住了。
最初,我们使用依赖项注入执行以下操作:
private readonly IRepository repository;
public MovieRepository(IRepository repository)
{
this.repository = repository;
}
public Movie Get(int id)
{
return (from movie in repository.Query<Movie>()
select new Movie
{
ID = movie.ID,
Title = movie.Title,
Genre = new Genre
{
ID = movie.Genre.ID,
Name = movie.Genre.Name,
},
MaleLead = movie.MaleLead,
FemaleLead = movie.FemaleLead,
}).FirstOrDefault();
}
//Repository Query method in Repository.cs
public IQueryable<TEntity> Query<TEntity>() where TEntity : OurEntity
{
session = session.OpenSession();
return from entity in session.Query<TEntity>() select entity;
}
这非常适合我们当前的使用。我们以这种方式编写东西来保持对查询的控制,尤其是与更复杂的对象有关的查询,以确保我们能够准确地获得所需的信息。
我已经尝试了一些方法,例如使Query方法返回Task >并使用ToListAsync()方法,但是由于我将其作为那种列表返回,因此无法对其进行查询。
我确定我错过了一些东西。如果有人可以帮助我,我将不胜感激。
答案 0 :(得分:0)
在这种情况下,您需要使用FirstOrDefaultAsync
。
public async Task<Movie> Get(int id)
{
return await (from movie in repository.Query<Movie>()
select new Movie
{
ID = movie.ID,
Title = movie.Title,
Genre = new Genre
{
ID = movie.Genre.ID,
Name = movie.Genre.Name,
},
MaleLead = movie.MaleLead,
FemaleLead = movie.FemaleLead,
}).FirstOrDefaultAsync();
}
答案 1 :(得分:0)
将此using
语句添加到文件中
using NHibernate.Linq;
然后您可以将方法更改为
public async Task<Movie> Get(int id)
{
return await (from movie in repository.Query<Movie>()
select new Movie
{
ID = movie.ID,
Title = movie.Title,
Genre = new Genre
{
ID = movie.Genre.ID,
Name = movie.Genre.Name,
},
MaleLead = movie.MaleLead,
FemaleLead = movie.FemaleLead,
}).FirstOrDefaultAsync();
}
注意:这是only available from NHibernate 5
附录:
您在Repository.cs
中拥有的代码可以简化为以下形式:
//Repository Query method in Repository.cs
public IQueryable<TEntity> Query<TEntity>() where TEntity : OurEntity
{
//session = session.OpenSession(); //this is obviously wrong, but it's beside the point
var session = sessionFactory.OpenSession();
return session.Query<TEntity>(); //the fix
}