[英]Entity Framework projection behaviour
这里的第一篇文章非常简单。
我一直在研究在我正在开发的应用程序中简化一些复杂的查询,我在下面稍微讨论一下。
所以说我有这两个类:
域实体“EmailRecipient”(与EF代码优先使用,因此期望使用相同的列名生成SQL表)。
public class EmailRecipient
{
public Guid Id { get; set; }
public string FriendlyName { get; set; }
public string ExchangeName { get; set; }
public string Surname { get; set; }
public string Forename { get; set; }
public string EmailAddress { get; set; }
public string JobTitle { get; set; }
public virtual List<SentEmail> SentEmails { get; set; }
}
和一个名为“EmailLite”的JSON序列化的简单类定义为
public class EmailLite
{
public string EmailAddress { get; set; }
public Guid Id { get; set; }
public string FriendlyName { get; set; }
}
在我的专业EF6(.1.3)DbContext中,我有一个名为EmailRecipients的DbSet。
所以自然地对EmailRecipients执行这个linq表达式
EmailRecipients.Select(x => new EmailLite
{
Id = x.Id,
EmailAddress = x.EmailAddress,
FriendlyName = x.FriendlyName
});
生成的SQL是
SELECT
1 AS [C1],
[Extent1].[Id] AS [Id],
[Extent1].[EmailAddress] AS [EmailAddress],
[Extent1].[FriendlyName] AS [FriendlyName]
FROM [dbo].[EmailRecipients] AS [Extent1]
那么为什么我这样做:
Func<EmailRecipient, EmailLite> projectionFunction = x => new EmailLite
{
Id = x.Id,
EmailAddress = x.EmailAddress,
FriendlyName = x.FriendlyName
};
EmailRecipients.Select(projectionFunction);
如何获得以下(完整)SQL生成:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[FriendlyName] AS [FriendlyName],
[Extent1].[ExchangeName] AS [ExchangeName],
[Extent1].[Surname] AS [Surname],
[Extent1].[Forename] AS [Forename],
[Extent1].[EmailAddress] AS [EmailAddress],
[Extent1].[JobTitle] AS [JobTitle],
[Extent1].[SubscribedOn] AS [SubscribedOn]
FROM [dbo].[EmailRecipients] AS [Extent1]
非常感激任何的帮助!
干杯,周六
IQueryable<T>.Select()
将Expression<Func<T,TOut>>
作为参数,你实际使用的函数是IEnumerable<T>.Select()
,它接受一个委托。 因此,你告诉EF,从那一刻开始,你正在使用IEnumerable
而不是IQueryable
,其余的查询将在内存中执行=>你正在获取所有列。
EmailRecipients <-- in memory from here on --> .Select(projectionFunction);
您需要做的就是将projectionFunction
更改为表达式,它将起作用:
Expression<Func<EmailRecipient, EmailLite>> projectionFunction = x => new EmailLite
{
Id = x.Id,
EmailAddress = x.EmailAddress,
FriendlyName = x.FriendlyName
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.