是否可以用表达式替换赋值

本文关键字:替换 赋值 表达式 是否 | 更新日期: 2023-09-27 17:54:55

我有一个Web API控制器的方法,它查询DB并返回数据:

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 = ????有可能吗?

注意:我知道我可以使用扩展方法,也可以使用切换用例来提高可读性。然而,上面的代码是在实体框架的上下文中使用的,并且必须是一个表达式。这也排除了Expression.Compile()的使用。

是否可以用表达式替换赋值

如果没有一些表达式帮助程序库,这是不可能的。

以下是使用AsExpandableInvoke扩展方法使用LinqKit的方法:

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