Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

c# - Entity Framework Core Where All

I can do this fine in EF.Net, but not in EFCore

List<string> keyList = string.IsNullOrEmpty(keywords) ? new List<string>() : keywords.Split(' ').ToList();

collections = await db.ProductCollections
    .Where(m => m.Children.Count == 0 && (!keyList.Any() ? true : keyList.All(x => m.Name.Contains(x))))
    .ToListAsync();

I changed it into:

collections = await db.ProductCollections
    .Where(m => m.Children.Count == 0 && (keyList.Count == 0 || keyList.All(x => m.Name.Contains(x))))
    .ToListAsync();

So I guess the problem is in keyList.All(). How can I achieve this in EFCore?

The error message:

The LINQ expression 'DbSet() .Where(p => DbSet() .Where(p0 => EF.Property<Nullable>(p, "ID") != null && object.Equals( objA: (object)EF.Property<Nullable>(p, "ID"), objB: (object)EF.Property<Nullable>(p0, "ParentId"))) .Count() == 0 && False || __keyList_0 .All(x => p.Name.Contains(x)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

question from:https://stackoverflow.com/questions/65557753/entity-framework-core-where-all

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Alternative approach to build query based on key list, before executing it.

var keys = string.IsNullOrEmpty(keywords) ? Array.Empty<string>() : keywords.Split(' ');

var query = db.ProductCollections.Where(p => p.Children.Any() == false);
foreach (var key in keys)
{
     query = query.Where(p => p.Name.Contains(key));
}

var collections = await query.ToListAsync();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...