public class News
{
public virtual int Id { set; get; }
public virtual string Title { get; set; }
public virtual string Thumbnail { set; get; }
public virtual string Image { set; get; }
public virtual string NewsContent { set; get; }
public virtual DateTime DateCreated { set; get; }
public virtual bool Published { set; get; }
public virtual int UserCreated { set; get; }
public virtual Category Category { set; get; }
public virtual DateTime DateUpdated { set; get; }
public virtual int ViewCount { set; get; }
}
我有这个类,我想查询数据库以获得结果。这是我的疑问:
foreach (var category in categories)
{
var news = newsRepo.Query("from News n where n.Category ="+category);
}
这是查询方法。
public IQueryable<T> Query(string query)
{
IQueryable<T> queryable;
using (var session = SessionFactory.OpenSession())
using (var transaction = session.BeginTransaction())
{
var hql = session.CreateQuery(query);
var list = hql.List<T>();
queryable = list.AsQueryable();
transaction.Commit();
}
return queryable;
}
并且它不起作用。
我收到以下错误:
could not execute query
[ select news0_.Id as Id13_, news0_.Title as Title13_, news0_.DateCreated as DateCrea3_13_, news0_.DateUpdated as DateUpda4_13_, news0_.NewsContent as NewsCont5_13_, news0_.Published as Published13_, news0_.UserCreated as UserCrea7_13_, news0_.Image as Image13_, news0_.Thumbnail as Thumbnail13_, news0_.ViewCount as ViewCount13_, news0_.Category_id as Category11_13_ from [News] news0_ where news0_.Category_id=. ]
我该如何解决?
任何想法?
答案 0 :(得分:1)
如果你在下面一行代码中加上一个断点,那么你应该看到category
变量没有被初始化为你期望的值(应该是一个整数):
var news = newsRepo.Query("from News n where n.Category ="+category);
除此之外,有几种更好的方法可以促进此查询。一种是像这样使用Session.Get(id):
var news = Session.Get<News>(1);
你也可以像这样使用NHibernate LINQ提供程序:
var news = Session.Query<News>().SingleOrDefault();
绝对必要时仅使用文字SQL或HQL。