2016-04-14 6 views
5

ここに最初の投稿とかなり単純な投稿。Entity Framework投影の振る舞い

私は開発中のアプリケーションで複雑なクエリを単純化することを検討してきましたが、私は頭の中で少し傷ついています。

だから私はこれらの2つのクラスを持っていると言う:

ドメインエンティティ「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; } 
} 

と私の専門のEF6(.1.3)DbContextで

public class EmailLite 
{ 
    public string EmailAddress { get; set; } 
    public Guid Id { get; set; } 
    public string FriendlyName { get; set; } 
} 

と定義 "EmailLite" と呼ばれるJSONのシリアル化のための単純なクラス、私はDbSetがEmailRecipientsと呼ばれています。

だから、自然に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] 

ご協力いただければ幸いです。

乾杯、 土

答えて

3

IQueryable<T>.Select()がパラメータとしてExpression<Func<T,TOut>>を取り、あなたが実際に使用している機能は、デリゲートをとるIEnumerable<T>.Select()です。このため、あなたはではなくIEnumerableではなく、クエリの残りの部分がメモリで実行される=>すべての列をフェッチしていることをEFに伝えています。

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