NHibernate查询失败

本文关键字:失败 查询 NHibernate | 更新日期: 2023-09-27 18:29:32

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=. ]

我该如何解决它?

有什么想法吗?

NHibernate查询失败

如果在以下代码行放置一个断点,那么您应该看到 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。