我有以下 linq 选择查询,它循环链接到以 B 开头的“adrianMember”的所有“Places”,我只想显示 PlaceName。我有一个从成员到地方的导航关联,但没有从地方到成员的导航关联。
using (var fdb = new FALDbContext())
{
var adrianMember = fdb.Members.Find(1);
foreach (string s in adrianMember.Places.Where(p=>p.PlaceName.StartsWith("B")).Select(p => p.PlaceName))
{
Console.WriteLine("- " + s);
}
}
我也尝试过各种 linq 语法,例如不使用 Find ...
var adrianMember = fdb.Members.Where(m => m.MemberId == 1).FirstOrDefault();
并提供两个 linq 查询,一个用于检索成员,然后检索相关位置(并希望使 EF 进行一些延迟延迟加载),但这仍然导致 sql 效率非常低。
using (var fdb = new FALDbContext())
{
//Need the FirstOrDefault otherwise we will return a collection (first or default will return the inner collection
//could have multiple members with multiple places
var members = fdb.Members.Where(m=>m.FirstName == "Bob");
foreach (var member in members)
{
var places = member.Places.Where(p => p.PlaceName.StartsWith("B")).Select(p => p.PlaceName);
foreach (var place in places)
{
Console.WriteLine(place);
}
}
}
SQL 输出获取所有行和所有列
exec sp_executesql N'SELECT
[Extent1].[PlaceId] AS [PlaceId],
[Extent1].[PlaceName] AS [PlaceName],
[Extent1].[PlaceLocation] AS [PlaceLocation],
[Extent1].[Member_MemberId] AS [Member_MemberId]
FROM [dbo].[Places] AS [Extent1]
WHERE [Extent1].[Member_MemberId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
有没有办法将 sql 限制为类似
SELECT PlaceName FROM Places WHERE MemberId = 1 AND PlaceName like 'B%'
我的项目中有几种情况,上面生成的 sql 会使查询太慢(每个成员 20,000 条记录超过 20 列)。如果我确实有更多记录,linq 是否足够聪明以进行更改?