【问题标题】:Getting Exception when using NHibernate 2.1 Linq<T> , why?使用 NHibernate 2.1 Linq<T> 时出现异常,为什么?
【发布时间】:2011-11-28 07:56:18
【问题描述】:

当使用带有 Linq 程序集的 NHibernate 2.1 时,我们在尝试枚举结果或调用 ToList() 时遇到异常。

我们有一个Id的列表,我们想获取它们的记录,我们使用了以下代码

public List<TEntity> GetAllContainsItems<TEntity>(List<int> ids) 
    where TEntity : IEntity
{
    using (IUnitOfWork uof = _container.Resolve<IUnitOfWork>())
    {
        uof.Initialize();

        IRepository<TEntity> rep 
            = _container.Resolve<IRepository<TEntity>>();

        // repository exposes the ISession.Linq<T> of nhibernate.
        var res = rep.Find().Where(y => ids.Contains(y.Id) );

        // get the exception:
        // "Object reference not set to an instance of an object."

        return res.ToList();
    }
}

有什么想法吗?

附: 我们暂时无法更改 Dll。

【问题讨论】:

  • Select(x => x) 似乎是多余的。有什么具体原因吗?
  • 另外,难道ids 就是null?我建议您在方法的顶部检查它,如果是,则抛出 ArgumentNullException
  • 抱歉,Select 是我的检查,它不应该存在。 ids 不为空,在执行 Find() 时我得到所有记录
  • 您是否有堆栈跟踪来指示异常源自哪个组件?

标签: c# linq nhibernate


【解决方案1】:

你能不能把你的代码改成下面这样,看看是否有效:

if(ids==null)
{
   Console.WriteLine("Why am I not surprised");
}
var res = rep.Find().Where(y => y!=null && ids.Contains(y.Id));
return res.ToList();

【讨论】:

  • rep.Finq() 只是暴露了 Nhibernate 的 ISession.Linq
  • 仍然返回相同的异常,如果我只是将其保留为 Find,我将获得整个记录集。有可能它是一个 Nhibernate 错误吗?
  • 我不这么认为。我可以看到 Find() 的实现吗?也再次更新答案
  • 我喜欢你的Console.WriteLine ... 有一些信心,但是当我说数据不为空时,答案是相信我,由于数据rep.Find().AsEnumerable().Where(x =&gt; ids.Contains(x.Id)) 的负载,以下代码确实有效
  • 对不起,但有时你需要确定:D!哦,等等,你想在你的数据库上运行这个查询吗?包含无法转换为 db 查询语句,并且数据被检索到 Web 服务器中。还有 Find() 实现请
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2018-09-24
  • 2017-09-21
  • 1970-01-01
相关资源
最近更新 更多