首页 \ 问答 \ 动态lambda表达式(OrderBy)和可空属性类型(Dynamic lambda expression (OrderBy) and nullable property type)

动态lambda表达式(OrderBy)和可空属性类型(Dynamic lambda expression (OrderBy) and nullable property type)

我正在尝试动态创建表达式,通过Entity Framework对数据库中的数据进行排序。 但我遇到了一个问题,无法克服它。 也许让我解释一下我想做什么。 我的目标是创建这样的表达式:

x => x.Property

其中“Property”是我想动态指定的属性名称。

现在,让我们转到类,它代表数据库中的表(我简化它以使事情更清晰):

public class MyModelClass
{
    public long MyLongProperty { get; set; }
    public decimal? MyNullableDecimalProperty { get; set; } // IMPORTANT: it's nullable
}

这是我的代码,我正在尝试创建前面描述的表达式:

// Db is EntityFramework context
IQueryable<MyModelClass> list = Db.MyModels.Select(x => x);

// x =>
var argument = Expression.Parameter(list.ElementType, "x");

// x.MyNullableDecimalProperty
var propertyToOrder = Expression.Property(argument, "MyNullableDecimalProperty");

// x => x.MyNullableDecimalProperty
var finalExpression = Expression.Call(
    typeof (Queryable),
    "OrderBy",
    new[] { list.ElementType, typeof(IComparable) },
    list.Expression,
    Expression.Lambda<Func<MyModelClass, IComparable>>(propertyToOrder, argument));

list = list.Provider.CreateQuery<MyModelClass>(finalExpression);

第4个语句出现问题(var finalExpression = Expression.Call(...))。 我得到一个例外:

“System.Nullable`1 [System.Decimal]”类型的表达式不能用于返回类型“System.IComparable”。

据我所知,问题在于我使用“IComparable”类型,其中“MyNullableDecimalProperty”是Nullable,而Nullable不是用户IComparable接口。 当我通过“MyLongProperty”订购或更换“IComparable”时,不会抛出异常。

所以我的问题:

  1. 我应该使用什么类型来使它适用于任何可以为空的属性?

  2. 是否可以使用一种类型,它将适用于所有属性,无论它们是可空的还是不可空的。

注意:我知道我可以使用ex。 动态Linq库,但我对这个解决方案不感兴趣 - 我想学习如何在不使用第三方库的情况下克服它。


I'm trying to dynamically create expression that will sort data from database through Entity Framework. But I encountered one problem and cannot overcome it. Maybe let me explain what I'm trying to do. My goal is to create expression like this:

x => x.Property

Where "Property" is the name of property which I'd like to specify dynamically.

Now, let's go to the class, which represents the table in database (I simplified it to make things more clear):

public class MyModelClass
{
    public long MyLongProperty { get; set; }
    public decimal? MyNullableDecimalProperty { get; set; } // IMPORTANT: it's nullable
}

It is my code, where I'm trying to create expression described earlier:

// Db is EntityFramework context
IQueryable<MyModelClass> list = Db.MyModels.Select(x => x);

// x =>
var argument = Expression.Parameter(list.ElementType, "x");

// x.MyNullableDecimalProperty
var propertyToOrder = Expression.Property(argument, "MyNullableDecimalProperty");

// x => x.MyNullableDecimalProperty
var finalExpression = Expression.Call(
    typeof (Queryable),
    "OrderBy",
    new[] { list.ElementType, typeof(IComparable) },
    list.Expression,
    Expression.Lambda<Func<MyModelClass, IComparable>>(propertyToOrder, argument));

list = list.Provider.CreateQuery<MyModelClass>(finalExpression);

Problem occurs at 4th statement (var finalExpression = Expression.Call(...)). I get an exception:

Expression of type „System.Nullable`1[System.Decimal]” cannot be used for return type „System.IComparable”.

As far I understand the problem is with me using "IComparable" type where "MyNullableDecimalProperty" is Nullable and Nullable doesn't user IComparable interface. The exception isn't thrown when I'm ordering by "MyLongProperty" or when I replace "IComparable".

So my questions:

  1. What type should I use to make it work with any nullable properties?

  2. Is it possible to use one type and it will work with all properties whether they are nullable or non-nullable.

Notice: I know I can use for ex. Dynamic Linq library, but I'm not interested in this solution - I'd like to learn how to overcome it without using 3rd party libraries.


原文:https://stackoverflow.com/questions/32098485
更新时间:2022-06-13 18:06

最满意答案

来自一个美丽的网站: http//www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/

 var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };

    if(isMobile.any()){
        // Mobile!
    } else {
        // It is desktop
    }

否则使用像device.js这样的库http://matthewhudson.me/projects/device.js/


From a beautiful site: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/

 var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };

    if(isMobile.any()){
        // Mobile!
    } else {
        // It is desktop
    }

Else use libraries like device.js http://matthewhudson.me/projects/device.js/

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。