2016-07-05 5 views
0

私は、DBを照会し、データを返すWeb APIコントローラーの方法があります。式を使用して代入を置き換えることは可能ですか?

public IQueryable<DeviceInformation> GetAllRegisteredDevices() 
{ 
    var result = this.db.CustomDeviceInstallations.Select(install => new DeviceInformation 
    { 
     Platform = 
      install.Platform == NotificationPlatform.Apns ? PLATFORM.iOS : 
      install.Platform == NotificationPlatform.Gcm ? PLATFORM.Android : 
      PLATFORM.Unknown 
    }); 

    return result; 
} 

割り当てられているプラ​​ットフォームについての決定である。この方法ではどのようなバグを私に。私は、他のコンテキストで同じ決定が必要になりますので、それを抽出したいと思いますので、私はなってしまった:

public Expression<Func<NotificationPlatform, PLATFORM>> ToDeviceInfoPlatformExpression() 
{ 
    return p => 
     p == NotificationPlatform.Apns ? PLATFORM.iOS : 
     p == NotificationPlatform.Gcm ? PLATFORM.Android : 
     PLATFORM.Unknown; 
} 

質問は今ある:どのように私は私の表現を使うことができますか? Platform = ????それはまったく可能ですか?

注:私は代わりに拡張メソッドを使用でき、可読性のためにスイッチケースを使用することもできます。ただし、上記のコードはEntity Frameworkのコンテキストで使用され、式でなければなりません。これはまた、Expression.Compile()の使用を除外します。

+0

あなたがすべてで式ツリーを使用している理由は不明です。元のコードに何が問題なのですか? –

+0

主に好奇心。セカンダリ:コードをコピーせずに同じ割り当てを複数回実行する。 – Krumelur

+0

うわー、率直に言って、私は「近い」投票と下の投票に驚いています。私はこれが面白い質問だと思った。しかし、私は完全に間違っていたようです。 – Krumelur

答えて

1

一部の表現ヘルパーライブラリなしでは不可能です。ここで

あなたはLinqKitAsExpandableInvoke拡張メソッドを使用していることを行うことができる方法である。

// First you need to put the expression into a variable 
// Without that you'll get the famous EF method not supported exception 
var deviceInfoPlatform = ToDeviceInfoPlatformExpression(); 
// Then you can use it inside the query 
var result = this.db.CustomDeviceInstallations 
    .AsExpandable() 
    .Select(install => new DeviceInformation 
    { 
     Platform = deviceInfoPlatform.Invoke(install.Platform) 
    }); 
関連する問題