【发布时间】:2021-01-08 23:13:55
【问题描述】:
我按照这些思路设置了一些实体:
public class Person
{
public int PersonId {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
}
public class Event
{
public int EventId {get;set;}
public int PersonId {get;set;}
public virtual Person {get;set;}
}
我还有一个从我的存储库中提取的自定义方法
public IQueryable<T> FindByCondition(Expression<Func<T, bool>> expression)
{
return this.RepositoryContext.Set<T>().Where(expression).AsNoTracking();
}
我还有一个助手可以从 GET 查询中收集查询参数。 例如,我的事件参数助手可能有一个属性,如
public string EventCreator {get;set;}
带有示例 URL ..../event?eventcreator=tom
我遇到的问题是我希望 EventCreator 与人的全名匹配。如果我这样查询,它会起作用:
_repoWrapper.Event.FindByCondition(p => p.Person.FirstName.Contains(filterModel.EventCreator ?? String.Empty, StringComparison.InvariantCultureIgnoreCase))
.Where(p => p.Person.LastName.Contains(filterModel.EventCreator ?? String.Empty, StringComparison.InvariantCultureIgnoreCase))
但是,显然如果查询包含部分或全部名字和姓氏,这将不匹配。
我想做的是这样的,但它不想工作
_repoWrapper.Event.FindByCondition(p => String.Format("{0}{1}", p.Person.FirstName, p.Person.LastName).Contains(filterModel.EventCreator ?? String.Empty, StringComparison.InvariantCultureIgnoreCase))
我收到如下错误:
Message "The LINQ expression 'DbSet<Event>\r\n .Join(\r\n outer: DbSet<Person>, \r\n inner: t => EF.Property<Nullable<int>>(t, \"PersonId\"), \r\n outerKeySelector: a => EF.Property<Nullable<int>>(a, \"PersonId\"), \r\n innerKeySelector: (o, i) => new TransparentIdentifier<Event, Person>(\r\n Outer = o, \r\n Inner = i\r\n ))\r\n .Where(t => string.Format(\r\n format: \"{0}{1}\", \r\n arg0: t.Inner.FirstName, \r\n arg1: t.Inner.LastName).Contains(\r\n value: __p_0, \r\n comparisonType: InvariantCultureIgnoreCase))' 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 either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information." string
有人知道这里发生了什么吗?
【问题讨论】:
-
如何使用.Join() 和正则表达式?
-
您能详细说明一下吗?我是 EF 新手
-
我使用 EF/linq 的方式不同,我设置了数据库,然后,我有一些 dbContext,并直接使用表或类,我要做的是获取列表对象,然后使用 .Where(o => o.firstname.Contains(xxx)),一旦我让它们加入它们但正确地看到类,我认为你不应该加入它们,因为一个应该包括另一个
-
顺便问一下,你能举个例子说明你的追求吗?
-
我认为单独使用 linq 没有一个好的方法。您必须首先编写逻辑来从搜索词中提取名字和姓氏并单独比较列。您可以编写一些 sql 来执行此操作,将列连接起来并进行比较,但我认为性能不会很好(当然取决于行数),但是 EF 无法弄清楚如何为您编写该 sql ...也许写连接列和模型的视图。只用于搜索? (虽然不确定性能)
标签: c# mysql asp.net entity-framework