我有一个简单的EF7代码优先模型:Countries
有States
,States
有Cities
。定义关系和反向关系,以便可以双向遍历导航字段和集合。
我想在所有城市上运行文本搜索:将搜索词分开以逐个搜索每个单词,搜索目标城市名称,州名和国家名称,并使此搜索包含在内(如果我寻找'法国德国弗朗西斯科',来自法国的城市,德国和旧金山的城市将包括在搜索结果中。)
为实现这一目标,我正在使用LinqKit的PredicateBuilder
构建我的搜索谓词。
当我在一个简单的内存中的实体集合中测试谓词构建和运行代码时,一切都按预期工作。
当我在Entity Framework 7上下文中针对Cities DbSet运行它时,我有这个奇怪的异常(System.InvalidCastException 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.ParameterExpression'
)。
我首先认为它与LinqKit有关,但它实际上与在查找涉及2级关系的字段时使用带有EF7的PredicateBuilder有关:
// simple snippet, full code is below.
// the part that causes the exception is when accessing c.State.Country.Name
predicate = predicate.Or(c =>
c.StateId > 0 &&
c.State.CountryId > 0 &&
c.State.Country.Name.Contains(word));
在谓词构建代码中,您会注意到我构建了3个级别:
谓词构建过程显然以假初始化开始,然后与每个单词和每个字段目标进行OR运算。在发布之前,我尝试了以下尝试,如前面有关类似内容的问题所述:
Expand()
(提示:它没有帮助!)Expression
变量而不是匿名lambda(不是更好)Name.Contains
部分,但保持Id的2级遍历。在这种情况下,它不会崩溃(但当然没有完成文本查找)。这是一个完整的再现代码(创建一个localDb数据库,播种它,然后运行崩溃的代码)。
这是一个.Net 5控制台包项目,您需要将以下NuGet包添加到project.json文件中:
"dependencies": {
"LinqKit": "1.1.3.1",
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.Core": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"
}
控制台应用程序的C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using LinqKit;
using Microsoft.Data.Entity;
namespace LinqKitIssue
{
public abstract class BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Country : BaseEntity
{
public virtual ICollection<State> States { get; set; } = new List<State>();
}
public class State : BaseEntity
{
public int CountryId { get; set; }
public virtual Country Country { get; set; }
public virtual ICollection<City> Cities { get; set; } = new List<City>();
}
public class City : BaseEntity
{
public int StateId { get; set; }
public virtual State State { get; set; }
public override string ToString() => $"{Name}, {State?.Name} ({State?.Country?.Name})";
}
// setup DbContext
public class MyContext : DbContext
{
public DbSet<City> Cities { get; set; }
public DbSet<State> States { get; set; }
public DbSet<Country> Countries { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=LinqKitIssue;Trusted_Connection=True;MultipleActiveResultSets=true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Country>().HasMany(c => c.States).WithOne(c => c.Country).HasForeignKey(s => s.CountryId);
modelBuilder.Entity<State>().HasMany(c => c.Cities).WithOne(c => c.State).HasForeignKey(c => c.StateId);
modelBuilder.Entity<City>().HasOne(f => f.State);
}
}
public class Program
{
public static void Main(string[] args)
{
// Seed with all cities
SeedData.Seed();
// search parameters
var searchInput = "los las british france";
var searchWords = searchInput.Split(' ');
// will be looking for each word, inclusively
var predicate = PredicateBuilder.False<City>();
// iterate to look for each word
foreach (var word in searchWords)
{
// Level 0 : look for the word at each level : city (ok with in-mem and ef)
predicate = predicate.Or(c => c.Name.Contains(word));
// Level 1 : then state (ok with in-mem and ef)
predicate = predicate.Or(c =>
c.StateId > 0 &&
c.State.Name.Contains(word));
// Level 2 : then country (ok with in-mem, crashes with ef)
predicate = predicate.Or(c =>
c.StateId > 0 &&
c.State.CountryId > 0 &&
c.State.Country.Name.Contains(word));
}
// apply
Console.WriteLine($"Search results for : '{searchInput}'");
using (var ctx = new MyContext())
{
var query = ctx.Cities.AsQueryable();
// includes
query = query.Include(c => c.State).ThenInclude(s => s.Country);
// search
var searchResults = query.Where(predicate).ToList();
searchResults.ForEach(Console.WriteLine);
}
}
}
public static class SeedData
{
public static void Seed()
{
using (var ctx = new MyContext())
{
ctx.Database.EnsureDeleted();
ctx.Database.EnsureCreated();
// countries
var us = new Country { Name = "united states" };
var canada = new Country { Name = "canada" };
ctx.Countries.AddRange(us, canada);
ctx.SaveChanges();
// states
var california = new State { Name = "california", Country = us };
var nevada = new State { Name = "nevada", Country = us };
var quebec = new State { Name = "quebec", Country = canada };
var bc = new State { Name = "british columbia", Country = canada };
ctx.States.AddRange(california, nevada, quebec, bc);
ctx.SaveChanges();
// Cities
var sf = new City { Name = "san francisco", State = california };
var la = new City { Name = "los angeles", State = california };
var lv = new City { Name = "las vegas", State = nevada };
var mt = new City { Name = "montreal", State = quebec };
var vc = new City { Name = "vancouver", State = bc };
ctx.Cities.AddRange(sf, la, lv, mt, vc);
ctx.SaveChanges();
}
}
}
}
下面是完整的堆栈跟踪(抱歉是法语,但我不想翻译它,法语单词与英语单词相比是透明的!)。
System.InvalidCastException: Impossible d'effectuer un cast d'un objet de type 'System.Linq.Expressions.FieldExpression' en type 'System.Linq.Expressions.ParameterExpression'.
à Microsoft.Data.Entity.Query.ExpressionVisitors.Internal.IncludeExpressionVisitor.VisitMethodCall(MethodCallExpression expression)
à System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
à Microsoft.Data.Entity.Query.ExpressionVisitors.ExpressionVisitorBase.Visit(Expression expression)
à System.Linq.Expressions.ExpressionVisitor.VisitArguments(IArgumentProvider nodes)
à System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
à Microsoft.Data.Entity.Query.ExpressionVisitors.Internal.IncludeExpressionVisitor.VisitMethodCall(MethodCallExpression expression)
à System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
à Microsoft.Data.Entity.Query.ExpressionVisitors.ExpressionVisitorBase.Visit(Expression expression)
à Microsoft.Data.Entity.Query.RelationalQueryModelVisitor.IncludeNavigations(IncludeSpecification includeSpecification, Type resultType, LambdaExpression accessorLambda, Boolean querySourceRequiresTracking)
à Microsoft.Data.Entity.Query.EntityQueryModelVisitor.IncludeNavigations(QueryModel queryModel, IReadOnlyCollection`1 includeSpecifications)
à Microsoft.Data.Entity.Query.RelationalQueryModelVisitor.IncludeNavigations(QueryModel queryModel, IReadOnlyCollection`1 includeSpecifications)
à Microsoft.Data.Entity.Query.EntityQueryModelVisitor.IncludeNavigations(QueryModel queryModel)
à Microsoft.Data.Entity.Query.EntityQueryModelVisitor.CreateQueryExecutor[TResult](QueryModel queryModel)
à Microsoft.Data.Entity.Storage.Database.CompileQuery[TResult](QueryModel queryModel)
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
à Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_0`1.<CompileQuery>b__0()
à Microsoft.Data.Entity.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
à Microsoft.Data.Entity.Query.Internal.QueryCompiler.CompileQuery[TResult](Expression query)
à Microsoft.Data.Entity.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
à Microsoft.Data.Entity.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
à Remotion.Linq.QueryableBase`1.GetEnumerator()
à System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
à System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
à LinqKitIssue.Program.Main(String[] args) dans d:\documents\visual studio 2015\Projects\LinqKitIssue\src\LinqKitIssue\Program.cs:ligne 98
--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
à Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
à Microsoft.Dnx.ApplicationHost.Program.<>c__DisplayClass3_0.<ExecuteMain>b__0()
à System.Threading.Tasks.Task`1.InnerInvoke()
à System.Threading.Tasks.Task.Execute()