【问题标题】:Linq query where contains List in a ListLinq查询其中包含列表中的列表
【发布时间】:2014-06-16 22:41:55
【问题描述】:

我正在尝试查询 MongoDB 以获取前 5000 条记录,这会导致以下错误。 我正在使用 C# LINQ 驱动程序,而 TermMonitorIds 是一个 BsonArray。

{“无法确定表达式的序列化信息:x.ToString()。”}

public IList<SocialRecord> GetManyBetweenDatesLimited(List<string> termMonitorIds, string[] sources, DateTime fr, DateTime to)
        {
            IList<SocialRecord> entities = new List<SocialRecord>();

            try
            {
                entities =
                    (from e in this.collection.AsQueryable<SocialRecord>()
                     where (e.TermMonitorIds.Any(x => termMonitorIds.Contains(x.ToString()))) && (sources.Contains(e.SocialType))
                                                             && (e.DateCreated.Date >= fr.Date) && (e.DateCreated.Date <= to.Date)
                     select e)
                    .Take(5000)
                    .ToList();
            }
            catch (Exception ex)
            {
                Log.Error("Error Message", ex);
            }

            return entities;
        }

我尝试将 List 更改为 BsonArray,如下所示:

BsonArray bArray = new BsonArray();
            foreach (var term in termMonitorIds )
            {
                bArray.Add(term.ToBson());
            }

仍然会出现如下错误消息:

“/”应用程序中的服务器错误。

字符串值不能写入 BSON 文档的根级别。

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.InvalidOperationException:无法将字符串值写入 BSON 文档的根级别。

【问题讨论】:

  • 你用的是什么版本的MongoDB?
  • MongoDb 2.4.9 版本

标签: c# linq


【解决方案1】:

LINQ 提供程序不支持 ToString,因为它不知道如何将其转换为 MongoDB 表达式。

我建议您更新 termMonitorIds 以匹配 e.TermMonitorIds 返回的预期数据类型,例如List&lt;int&gt; / List&lt;Guid&gt;,避免了任何类型的转换(没有它通常会更有效)。

【讨论】:

  • LINQ to SQL?我不这么认为:-)
  • @sloth 是的,我意识到我写的东西我写完之后哈哈
猜你喜欢
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多