使用 ODataQueryOptions 时,LINQ to Entities 不支持类型成员"Age"



我们在应用程序中不断选择这样的数据:

myDummyService.getAll().Where(x => x.Id > 1000).Select(x => new DummyDto() {
Id = x.Id,
Name = x.Name
};

这将返回一个IQueryableDummyDto如下所示:

public class DummyDto {
public int Id {get;set;}
public string Name {get;set;}
public int Age {get;set;}
}

一旦我们使用ODataQueryOptions来实现分页,就会导致错误:

The specified type member "Age" is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

"年龄"只是DummyDto的另一个属性,我们在上面的代码中没有选择。

我们像这样实现分页:

public PageResult<DummyDto> GetAll(ODataQueryOptions<DummyDto> queryOptions) {
var result = queryOptions.applyTo(
myDummyService.getAll().Where(x => x.Id > 1000).Select(x => new DummyDto() {
Id = x.Id,
Name = x.Name
})
});
return new PageResult<DummyDto>(results as IEnumerable<DummyDto>);

如果我们将查询更改为此查询,则错误将消失。

public PageResult<DummyDto> GetAll(ODataQueryOptions<DummyDto> queryOptions) {
var result = queryOptions.applyTo(
myDummyService.getAll().Where(x => x.Id > 1000).Select(x => new DummyDto() {
Id = x.Id,
Name = x.Name,
Age = null // simply set the property to null, because we don't want / need it in this case
})
});

有人知道为什么吗?

据我所知,queryOptions.applyTo()正在尝试将选项应用于类的每个属性,但不能使用Age,因为它没有连接到数据库对象。

我们只是创建一个新类,只是为了这个?

public class DummyDto2 {
public int Id {get;set;}
public string Name {get;set;}
}

年龄在您的模型中不是可为空的值,并强制完全分配空值,这就是出现错误的原因。

像这个模型一样声明您的财产

public int? Age {get;set;}

最新更新