![](/img/trans.png)
[英]A lambda expression with a statement body cannot be converted to an expression tree(Lambda and Linq)
[英]A lambda expression with a expression body cannot be converted to an expression tree C# entity framework
我有一个具有以下模型的实体表
public class VulnerabilityImportFileLog
{
public Collection<Vulnerability> Vulnerability { get; set; }
}
尝试使用实体框架查询中的 select 语句返回字符串值
var vulnerabilityImportFileLogSelect = vulnerabilityImportFileLogQuery
.Select(vulnerabilityImportFileLog =>
new VulnerabilityImportedScansListViewDto
{
AssetName = vulnerabilityImportFileLog.Vulnerability.Select(y =>
{
if (y.AssetHostIPOrDomain.HostIPAssetId.HasValue)
return y.AssetHostIPOrDomain.HostIPAsset.Title;
else if (y.AssetHostIPOrDomain.DomainAssetId.HasValue)
return y.AssetHostIPOrDomain.DomainAsset.Title;
else
return y.AssetHostIPOrDomain.HostIPOrDomain;
}
).Distinct().ToList()
});
其中AssetName
的类型为List<string>
并获得异常为A lamda expression with a statement body cannot be converted to an expression tree
建议的答案是使用AsEnumerable()
,但即使这样也不能解决问题。
您可以通过使用带有“let”关键字的 linq 查询语法来解决该问题:
AssetName = (from y in vulnerabilityImportFileLog.Vulnerability
let resultString = y.AssetHostIPOrDomain.HostIPAssetId.HasValue
? y.AssetHostIPOrDomain.HostIPAsset.Title
: y.AssetHostIPOrDomain.DomainAssetId.HasValue
? y.AssetHostIPOrDomain.DomainAsset.Title
: y.AssetHostIPOrDomain.HostIPOrDomain
select resultString
)
.ToList()
.Distinct();
假设脆弱性ImportFileLogQuery 是一个IQueryable<vulnerabilityImportFileLog>
那么从关联的漏洞关系中获取详细信息的典型方法是通过SelectMany
。 鉴于您需要根据可用的内容进行替换,一种选择是进行双重投影。 第一遍选择并实现我们想要检查的细节,然后第二遍组成结果。
vulnerabilityImportFileLogQuery.SelectMany(x => new
{
x.Vulnerability.AssetHostIpOrDomain.HostIpOrDomain,
HostIpAssetTitle = x.Vulnerability.AssetHostIpOrDomain.HostIpAsset.Title,
DomainAssetTitle = x.Vulnerability.AssetHostIpOrDomain.DomainAsset.Title
}).ToList()
.Select(x => x.HostIpAssetTitle ?? DomainAssetTitle ?? HostIpOrDomain)
.Distinct()
.ToList();
这实际上是从 HostIpAsset 和 DomainAsset 中获取 3 个值、我们的默认 HostIpOrDomain 值以及 Titles(如果它们可用)。 如果实体未关联或 Title 为 #null,则 EF 将返回 #null。 这个查询是使用ToList
实现的,然后我们根据空检查选择要使用的标题,然后再获取我们的 Distinct 集。
希望这能给你一些想法作为起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.