我有一个简单的查询如下:
var employeeTeam = Session.Query<EmployeeTeam>()
.Where(x => x.StartEffective <= competency.FinalDate && // competency.FinalDate is a DateTime
employeesIds.Contains(x.EmployeeId)) // employeeIds is a List<long>
.OrderByDescending(x => x.StartEffective)
.Select(x => new
{
x.EmployeeId,
x.StartEffective,
x.Team
}).ToList();
它成功运行了一次,但是在第二次执行时(或第三次、第四次等等)它抛出了一个无效的转换异常,例如:
Fatal Error:System.InvalidCastException: Cannot convert type 'System.Linq.EnumerableQuery`1[<>f__AnonymousType0`3[System.Int64,System.DateTime,Team]]' to 'System.Collections.Generic.IEnumerable`1[<>f__AnonymousType0`3[System.Int64,System.DateTime,Team]]'. in NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression)
为勇敢起见,堆栈跟踪的其余部分被抑制了。
查询总是在错误发生前在数据库中执行。它不返回任何记录,但没关系。如果我重建解决方案并再次运行,查询将再次在第一次执行,然后在我运行它时开始相互抛出异常。其他查询每次都运行,没有任何问题。我不知道导致错误的原因。
很重要的一点是,这段代码运行在 CSharpCodeProvider 中。环境,但我不知道它是否能有所作为。
更新
即使是最简单的查询形式也会发生这种情况:
var employeeTeam = Session.Query<EmployeeTeam>()
.Select(x => new
{
x.Id
}).ToList();
它只是第一次运行正常。但是,如果我将 annon 对象从 { x.Id }
更改为 { x.TeamId }
,例如,它第一次运行正常,然后再次出现异常.
更新 2
我刚刚意识到,如果我将以下属性添加到 annon 对象,查询每次都有效:
Rnd = (new Random().Next(1, 999))
那么,可能是缓存问题?
更新 3
我将 NHibernate 从 3.3
更新到 4.0.0.4
,它解决了几乎所有问题,除了一个查询:
var query = session.Query<Holiday>()
.Select(x => new {
HoliDayCities = x.City.Select(c => c.Id).ToList(),
HoliDayStates = x.State.Select(s => s.Id).ToList(),
Date = new DateTime((int)(x.Year.HasValue ? x.Year : competencia.InitialDate.Year), (int)x.Month, (int)x.Day)
}).ToList();
错误信息:
GenericADOException: The value "{ HoliDayCities = System.Collections.Generic.List`1[System.Int64], HoliDayStates = System.Collections.Generic.List`1[System.Int64], Date = 01/02/2015 00:00:00 }" is not "<>f__AnonymousType1`3[System.Collections.Generic.List`1[System.Int64],System.Collections.Generic.List`1[System.Int64],System.DateTime]" and cannot be used on this collection. Parameter name: value
如果我像之前提到的那样在 Select
作用域上添加 Rnd()
函数,它就可以正常工作。该问题仅发生在匿名对象上。
最佳答案
看起来这是操作匿名类型和 NHibernate 的问题。我强烈建议返回一个简单的结果集,使用 ToList() 实现结果集,然后对该结果集进行投影。
var employeeTeam = Session.Query<EmployeeTeam>()
.Select(x => x)
.Where(x => x.Id != 0)
.ToList();
var projectedTeam = employeeTeam.Select(x => new {x.Id});
关于c# - NHibernate 查询只运行一次,然后抛出 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088878/