How to use Enums with Dynamic Linq?

笑着哭i 提交于 2019-11-29 04:22:32

This works:

houses.AsQueryable<House>()
    .Where("MainRoom.Type = ConsoleApplication2.RoomType.Kitchen")

I encountered this same issue and tried the marked answer specified by @Steve Wilkes but it didn't work for me !! Then I discovered that dynamic LINQ has an HTML documentation in the same package which mentioned that Enums can be specified as String Literals.

houses.AsQueryable<House>().Where("MainRoom.Type = \"Kitchen\"")

Which worked for me.

This should work

houses.AsQueryable<House>().Where(rs=>rs.MainRoom.Type == RoomType.Kitchen);

Why do you need dynamic linq in this case? What output you expect

To my preference, use of error prone string should be avoided. If your class or property name changed, you won't be able to find the error until you encounter it.

Rather use expression

    Expression<Func<House, bool>> 
        filter = (p) => p.MainRoom.Type == RoomType.Kitchen; 
        filter = (p) => p.MainRoom.Area > 200;
        filter = (p) => p.Rooms.Sum(rs => rs.Area) > 500;
        filter = (p) => p.Address.Contains("abc");
        filter = (p) => p.Area > 200;
        ...
    var aRoomsHouses = houses.AsQueryable<House>().Where(filter);

You can create the expression where you decide which string filter to be used. Better create a static class or may be switch statement which gives you different type of expression which you can use as where argument.

in addition yet another variant use parameter

var aRoomsHouses = houses.AsQueryable<House>().Where("MainRoom.Type = @0",RoomType.Kitchen);
Amine

To add a new Enum type to dynamic linq, you must add the following code :

typeof(Enum),
typeof(T)

T : Enum type

in predefinedTypes of dynamic That's work for me;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!