如何查询实体框架中的名字和姓氏?

时间:2021-10-02 08:22:20

I want to have a fairly intelligent search box for finding objects by a person's name. In linq, it would look something like this:

我希望有一个相当智能的搜索框,用于按人名查找对象。在linq中,它看起来像这样:

users = users.Where(m => m.FirstName.Contains(query) || m.LastName.Contains(query) || (m.FirstName + " " + m.LastName).Contains(query) || (m.LastName + " " + m.FirstName).Contains(query) || (m.LastName + ", " + m.FirstName).Contains(query));

But this seems like it might be a bad way to do things, and I'm really not sure how performance degrades with Linq. Is this type of statement fine or is there a way to improve on this?

但这似乎是一种糟糕的做事方式,我真的不确定Linq的性能如何下降。这种声明是好还是有办法改进这个?

1 个解决方案

#1


EF is just going to convert the LINQ query to SQL and execute the SQL statement against the database. Your query above will translate to a where clause with an OR. Each contains() will translate to a like in SQL. So, you'll get something like:

EF只是将LINQ查询转换为SQL并对数据库执行SQL语句。您上面的查询将转换为带有OR的where子句。每个contains()将在SQL中转换为类似的。所以,你会得到类似的东西:

select *
from users
where FirstName like '%query%'
or LastName like '%query%'

As long as that resulting query performs okay, you should be fine.

只要生成的查询执行正常,您应该没问题。

If it doesn't perform well, you could look at adding an index or maybe using a full-text search.

如果效果不好,您可以查看添加索引或使用全文搜索。

https://msdn.microsoft.com/en-us/library/ms142571.aspx

#1


EF is just going to convert the LINQ query to SQL and execute the SQL statement against the database. Your query above will translate to a where clause with an OR. Each contains() will translate to a like in SQL. So, you'll get something like:

EF只是将LINQ查询转换为SQL并对数据库执行SQL语句。您上面的查询将转换为带有OR的where子句。每个contains()将在SQL中转换为类似的。所以,你会得到类似的东西:

select *
from users
where FirstName like '%query%'
or LastName like '%query%'

As long as that resulting query performs okay, you should be fine.

只要生成的查询执行正常,您应该没问题。

If it doesn't perform well, you could look at adding an index or maybe using a full-text search.

如果效果不好,您可以查看添加索引或使用全文搜索。

https://msdn.microsoft.com/en-us/library/ms142571.aspx