使用MongoDB的官方C#驱动程序进行按位枚举(标志)查询 [英] Bitwise enum (flags) query using MongoDB's official C# driver

查看:144
本文介绍了使用MongoDB的官方C#驱动程序进行按位枚举(标志)查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行以下形式的LINQ查询时:

When I try to run a LINQ query of the form:

MongoCollection<MyEntity> collection;

collection.AsQueryable().Where(entity =>
    (entity.Flags & MyFlags.AFlag) != MyFlags.None);

我收到消息Unsupported where clause: ((Int32)((Int32)entity.Flags & 4) != 0).

这是已知的错误/功能吗?

有什么解决方法吗?

文档看来,MongoDB进行了逐位更新,但没有更新按位查询.

From the documentation it seems like MongoDB has a bitwise update, but not a bitwise query.

为进行比较,使用ServiceStack作为客户端,同一查询在Redis上运行平稳.

For comparison, the same query runs smoothly above Redis using ServiceStack as a client.

我确实找到了这两个链接( link2 ),建议使用JavaScript,但这将使服务层的实现非常依赖于DB技术.

I did find these two links (link1, link2) which suggest using JavaScript, however, that would make the implementation of the service layer very dependant on the DB technology.

推荐答案

我的解决方案有两个部分. 我为Enum标志做了一个序列化程序,将所有值存储在字符串列表中. 我为Linq提供了一种扩展方法,以注入"我需要的mongo查询.

My solution has two parts. I made a serializer for Enum flags that stores all the values in a list of strings. I made an extension method for Linq to "inject" the mongo query i need.

public static IQueryable<TItem> HasFlags<TItem, TProperty>(
    this IQueryable<TItem> items,
    Expression<Func<TItem, TProperty>> itemPropertyExpression,
    params Enum[] enumFlags)
{
    var enumFlagNames = enumFlags.Select(enumFlag => (BsonValue)enumFlag.ToString());
    return items.Where(item => Query.In(ExtendedObject.GetPropertyName(itemPropertyExpression), enumFlagNames).Inject());
}

那样,它既可读又不需要将所有对象反序列化到内存中.

That way, its both readable and i don't need to deserialize all the objects into memory.

P.S:GetPropertyName方法只是获取属性名称的一种类型安全的方法:

P.S: The GetPropertyName method is just a type safe way to get the property name:

public static string GetPropertyName<TClass, TProperty>(
    Expression<Func<TClass, TProperty>> entityPropertyExpression)
{
    return ((MemberExpression)entityPropertyExpression.Body).Member.Name;
}

这篇关于使用MongoDB的官方C#驱动程序进行按位枚举(标志)查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆