我有RavenDB设置,通过WebApi层查询。 RavenDb层返回一个IQueriable,在WebApi层中应用OData过滤器。 RavenDB中保存的每个Employee对象都有一个与之关联的Version属性(保存文档时DateTime.UtcNow.Ticks的值)。最近我正在制定一个要求,我可以在一段时间内多次保存同一个Employee(作为单独的实体,它们的属性值不同但具有相同的Id),但我只想根据其Version值获取最新的一个
为了达到这个目的,我使用了MapReduce,如下所述:
public class Employee_Version : AbstractIndexCreationTask<Employee>
{
public Employee_Version()
{
Map = employees => from employee in employees
select new Employee
{
FirstName = employee.FirstName,
LastName = employee.LastName,
Departments = employee.Departments,
Id = employee.Id,
Version = employee.Version,
ManagerId = employee.ManagerId,
EmployeeId=employee.EmployeeId
};
Reduce = results => from result in results
group result by result.ManagerId
into g
select new
{
ManagerId = g.OrderByDescending(d => d.Version).First().ManagerId,
Departments = g.OrderByDescending(d => d.Version).First().Departments,
FirstName = g.OrderByDescending(d => d.Version).First().FirstName,
LastName = g.OrderByDescending(d => d.Version).First().LastName,
Version = g.OrderByDescending(d => d.Version).First().Version,
Id = g.OrderByDescending(d => d.Version).First().Id,
EmployeeId = g.OrderByDescending(d => d.Version).First().EmployeeId
};
}
}
Raven存储库代码:
public IQueryable<Employee> GetEmployees(Expression<Func<Employee, bool>> expression)
{
using (var session = DocumentStore.OpenSession())
{
return session.Query<Employee, Employee_Version>().Statistics(out querysStatistics).Where(expression),
}
}
Web Api图层代码:
Expression<Func<Employee, bool>> managerIdFilter = e => e.ManagerId == 123;
var employeeQueryable = _employeeRepository.GetEmployees(managerIdFilter);
var queryable = modelOptions.ApplyTo(employeeQueryable.Queryable, new ODataQuerySettings
{
EnableConstantParameterization = false,
HandleNullPropagation = HandleNullPropagationOption.False
});
当我查询它时:
http://localhost/employee/list?$顶部= 1
我得到以下例外:
内部ExcpetionUrl:\“/ databases / documents / indexes / Document / Version?&amp; query = ManagerId%3A123&amp; pageSize = 1&amp; sort = __ document_id&amp; SortHint -__ document_id = String \”\ \ \ \ System.ArgumentException:字段'__document_id'未编入索引,无法对未编入索引的字段进行排序
如果没有使用OData过滤器,则相同的查询可以正常工作。