实体框架投影行为

时间:2016-04-14 21:30:27

标签: c# entity-framework linq

这里的第一篇文章非常简单。

我一直在研究在我正在开发的应用程序中简化一些复杂的查询,并且我在下面稍微摸了一下。

所以说我有这两个类:

域实体" 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; }
}

和一个简单的JSON序列化类叫做#34; EmailLite&#34;定义为

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]

非常感谢任何帮助!

干杯, 饱和

1 个答案:

答案 0 :(得分:3)

IQueryable<T>.Select()Expression<Func<T,TOut>>作为参数,您实际使用的函数是IEnumerable<T>.Select(),它接受​​一个委托。因此,您告诉EF,从那一刻开始,您使用IEnumerable而不是IQueryable,其余查询将在内存中执行=&gt;你正在获取所有列。

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
};