问题描述
我目前正在尝试将 ID 列表与我的数据库实体的子属性相交。
这样做的目的是找到所有列表 ID 至少与子实体“位置”中的一个实体匹配的“表单”记录。 我相信 SQL 等价物会在连接表“Locations”上执行 IN。
所讨论元素的结构是这样的:(我有意省略了所有其他属性)。
public class Form
{
[Column("FormId"),DatabaseGenerated(DatabaseGeneratedOption.Identity),Key]
public Guid Id { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
public class Location
{
[Column("LocationId"),Key]
public Guid Id { get; set; }
}
我正在尝试执行以下操作:
var locationIdsL = locationIds.Split(',').Select(Guid.Parse).ToList();
return baseQuery.Include(x => x.Locations).Where(x => x.Locations.Select(y => y.Id).Intersect(locationIdsL).Count() == locationIdsL.Count);
* 假设 locationIdsL
变量是一个有效的 Guid 列表。
上面的代码返回以下异常:
System.ArgumentNullException:值不能为空。 (范围 '参数') 在 System.Linq.Expressions.Expression.Lambda(表达式主体,字符串 name,Boolean tailCall,IEnumerable`1 参数) at System.Linq.Expressions.Expression.Lambda(表达式主体, ParameterExpression[] 参数)在 Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.ReducingExpressionVisitor.Visit(Expression 表达式)在 System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor 访问者、 IArgumentProvider 节点)在 System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression) 节点)在 System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor 访客)在 System.Linq.Expressions.ExpressionVisitor.Visit(表达式节点)
但是,如果我像这样手动使用集合:
List<Form> forms = new List<Form>();
foreach (var form in baseQuery.Include(x => x.Locations))
{
var locations = form.Locations;
if (locations.Select(x => x.Id).Intersect(locationIdsL).Count() == locationIdsL.Count)
{
forms.Add(form);
}
}
forms
集合获得了我希望看到的项目,最值得注意的是,无一例外。
出于显而易见的原因,后者不是可接受的解决方案,因为它需要加载整个数据集。
我不确定这里缺少什么,因为 EFCore 应该能够翻译第一个查询。
老实说,我的方法可能完全错误,我可能完全“反模式”我的查询,我不确定;欢迎提出任何建议。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)