2016-04-14 61 views
5

這裏的第一篇文章很簡單。實體框架投影行爲

我一直在尋找簡化在我正在開發的應用程序中的一些複雜的查詢,我在我的頭上撓了一下。

所以說我有以下兩類:

域實體「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,我有一個名爲DbSet EmailRecipients。

所以很自然的執行對EmailRecipients

EmailRecipients.Select(x => new EmailLite 
     { 
      Id = x.Id, 
      EmailAddress = x.EmailAddress, 
      FriendlyName = x.FriendlyName 
     }); 

生成的SQL這個LINQ表達式是

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] 

任何幫助將不勝感激!

乾杯, 週六

回答

3

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

謝謝你 - 它必須是簡單的:我需要juuuuust再看仔細一點:)乾杯亞歷山大。 – sat1986