【发布时间】:2017-03-04 04:26:45
【问题描述】:
我可能使用了错误的方法来发起查询。这是带有 Sql Server 后端的 EF6。我有:
public IEnumerable<T> Select(string sessionId, Func<T, bool> predicate = null)
{
using (var databaseContext = new DatabaseContext())
{
var list = databaseContext.Set<T>().Where(predicate ?? (x => true)).AsQueryable<T>().ToList();
list.ForEach(o => o.SessionId = sessionId);
return list;
}
}
如果我用Select('sdfsdf', o => o.Category == 'Save Pewdiepie') 调用它,我希望它在sql 中放置一个where 子句,但是,它给了我这个没有where 子句:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[ClientId] AS [ClientId],
[Extent1].[Version] AS [Version],
[Extent1].[ReferenceNumber] AS [ReferenceNumber],
[Extent1].[RealExpirationDate] AS [RealExpirationDate],
[Extent1].[BusinessEffectiveDate] AS [BusinessEffectiveDate],
[Extent1].[BusinessExpirationDate] AS [BusinessExpirationDate],
[Extent1].[IsSuspended] AS [IsSuspended],
[Extent1].[RealEffectiveDate] AS [RealEffectiveDate],
[Extent1].[User] AS [User],
[Extent1].[Category] AS [Category]
FROM [dbo].[YouTube] AS [Extent1]
这对于大型表来说将是一个大问题。如何更改它以创建 where 子句?
【问题讨论】:
-
在你之前的几个 EF 帖子 - stackoverflow.com/questions/42585640/…。很快,将
Func<...>更改为Expression<Func<...>> -
@IvanStoev,如果我不想更改签名,如何将谓词包装在表达式中?
-
你不能。使用
Compile方法可以将Expression<Func<...>>转换为Func<...>,反之则不行。这是因为Expression更抽象(表达式树),可以转换为代码、字符串或在您的情况下 - 转换为 SQL。Func只是一个可以执行的代码。 -
请注意,从调用方来看,它们看起来很相似(在大多数情况下)。更改签名后您仍然可以使用
Select('sdfsdf', o => o.Category == 'Save Pewdiepie'):) -
@IvanStoev,您要回答,还是要我删除这个重复的问题?我的问题唯一独特之处在于我用更通俗的术语提出了这个问题。我最初的搜索没有找到现有的文章,因为它们充满了术语。
标签: sql-server entity-framework-6