【发布时间】:2020-01-29 21:23:19
【问题描述】:
我有一个方法:
我在其中定义了一个表达式,仅当输入参数userType 具有值时才会在 linq 查询中。
public Institution GetInstitutionWithServices(int institutionId, UserTypes? userType)
{
Expression<Func<Service, bool>> serviceUserTypeFilter = (s => true);
if (userType.HasValue)
{
serviceUserTypeFilter = (s => s.UserType == userType.Value);
};
var query = _dbContext.Institution.Include(a => a.Services)
.Where(a => a.Id == institutionId)
.Select(m => new Institution
{
Id = m.Id,
Name = m.Name
.Where(x => x.Status == Service.ServiceStatus.Published)
//&& userType.HasValue ? x.UserType == userType.Value : false )
.Where(serviceUserTypeFilter)
.ToList()
}).FirstOrDefault();
return query;
}
我不知道如何为具有外键的其他表(数据库上下文)添加过滤器。
它有服务。
在评论了我需要调用 thorugh 表达式的部分,因为我得到了该代码的空引用异常
我得到的这段代码的错误是:
错误 CS1503
参数 2:无法从 'System.Linq.Expressions.Expression<System.Func<Test001.Domain.Service, bool>>' 转换为 'System.Func<Test001.Domain.Service, bool>'
Test001.Repositories
【问题讨论】:
-
附带说明,您的
var query应命名为var result,因为它返回的是结果而不是查询本身。 -
当然@GSerg ..我会编辑它。谢谢
-
所以我需要用 Expression for SQL 包裹起来..
-
我无法摆脱您的查询似乎很奇怪的感觉,您的
Institution类成员Name正在使用List进行初始化,对吗?说说这行代码Name = m.Name.Where(x => x.Status == Service.ServiceStatus.Published).Where(serviceUserTypeFilter).ToList()