如何搜索具有string []数组属性的LINQ实体,并从string []数组中找到包含任何字符串的属性?

问题描述 投票:0回答:1

使用EF Core 2.2,我具有具有string[]数组属性的实体,其中在[[ApplicationDbContext中,它们使用以下方式检索:

modelBuilder.Entity<FruitBasket>() .Property(e => e.FruitTypes) .HasConversion( v => string.Join(',', v), v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
例如,一个实体垫在FruitType列中包含一个字符串数组:{"Apple", "Banana", "Orange"}在数据库中另存为:Apple,Banana,Orange

我正在尝试在数据库中查找包含输入字符串中任何字符串的所有对象,可以说以下任何一个:

string[] BasketSearchedFruitTypes = new string[] { "Apple", "Grapefruit", "Pineaple" }

我的IQueryable:

IQueryable<BasketModel> baskets = GetBasketsQueryable(); //BasketModel contains FruitType string[] prop

要搜索我现在有LINQ的实体,它说:

if (search.BasketSearchedFruitTypes != null && search.BasketSearchedFruitTypes.Length != 0) baskets = baskets .Where(data => search.BasketSearchedFruitTypes .Any(x => data.FruitType .Contains(x)));

不幸的是,它没有给我任何回报,我的想法也用光了。

编辑1:

使用表达式后:baskets = baskets .Where(data => search.BasketSearchedFruitTypes .Any(x => data.FruitType .Contains(x)));
当我尝试将其带到列表<>时,我得到的是ArgumentNullException。我也无法在其上使用foreach.Count()。我也有:

var result = baskets.Where(data => search.BasketSearchedFruitTypes.Intersect(data.FruitType).Any();

编辑2:

我刚刚指出,foreach循环通过返回的IQueryable,但是在某些时候会中断ArgumentNullException。甚至循环内的try catch也无济于事...

编辑3:

实际上,当我将返回的IQueryable的foreach放入try catch时,这是一种临时解决方案,并且可以正常工作。但是我仍然不明白为什么它在枚举时崩溃(循环,而不是循环内部的代码)。
c# arrays linq iqueryable ef-core-2.2
1个回答
0
投票
using System.Collections.Generic; using System.Linq; namespace ConsoleApp2 { class BuilderClass { List<BasketModel> baskets; public BuilderClass() { baskets = new List<BasketModel>() { new BasketModel { FruitType = new string[] { "Apple", "Grapefruit", "Pineaple", "Bing Cherry", "Cantaloupe" } }, new BasketModel { FruitType = new string[] { "Grapefruit", "Cantaloupe", "Pineaple", "Boysenberries", "Apple" } }, new BasketModel { FruitType = new string[] { "Clementine", "Bing Cherry", "Boysenberries", "Cantaloupe", "Entawak" } }, new BasketModel { FruitType = new string[] { "Entawak", "Grapefruit", "Apple", "Pineaple", "Cantaloupe" } }, new BasketModel { FruitType = new string[] { "Apple", "Pineaple", "Bing Cherry", "Entawak", "Grapefruit" } } }; } string[] BasketSearchedFruitTypes = new string[] { "Apple", "Grapefruit", "Pineaple" }; public void check() { var qbaskets = baskets.AsQueryable(); if (BasketSearchedFruitTypes != null && BasketSearchedFruitTypes.Length != 0) { var result = qbaskets.Where(data => BasketSearchedFruitTypes.Any(x => data.FruitType.Contains(x))).ToList(); // result have list with count of 4 } } } class BasketModel { public string[] FruitType { get; set; } } }
© www.soinside.com 2019 - 2024. All rights reserved.