【发布时间】:2020-05-17 12:01:32
【问题描述】:
我正在尝试使用 AsQueryable 和 LINQ 函数查询 mongodb 数据库。
我目前的数据库结构是我有一些集合,主要是在 C# 中定义的记录,如下所示:
public class Record
{
[BsonElement("formName")]
public string FormName { get; set; }
[BsonElement("created")]
public DateTime Created { get; set; }
[BsonElement("createdBy")]
public string CreatedBy { get; set; }
[BsonId]
[BsonIgnoreIfDefault]
[BsonRepresentation(BsonType.ObjectId)]
private string InternalId { get; set; }
[BsonElement("recordId")]
[Newtonsoft.Json.JsonProperty("recordId")]
public string Id { get; set; }
[BsonElement("organisationId")]
public string OrganisationId { get; set; }
// TODO: Consider making configurable
private string appName = "MediLog";
[BsonElement("appName")]
public string AppName
{
get { return this.appName; }
set { this.appName = value; }
}
[BsonElement("schemaVersion")]
public int SchemaVersion { get; set; }
[BsonElement("contents")]
public ExpandoObject Contents { get; set; }
[BsonElement("modified")]
public DateTime Modified { get; set; }
[BsonElement("modifiedBy")]
public string ModifiedBy { get; set; }
[BsonElement("majorVersion")]
public int MajorVersion { get; private set; }
[BsonElement("minorVersion")]
public int MinorVersion { get; private set; }
[BsonElement("version")]
public string Version
{
get
{
return (MajorVersion + "." + MinorVersion);
}
set
{
MajorVersion = Convert.ToInt32(value?.Substring(0, value.IndexOf(".", StringComparison.OrdinalIgnoreCase)), CultureInfo.InvariantCulture);
MinorVersion = Convert.ToInt32(value?.Substring(value.IndexOf(".", StringComparison.OrdinalIgnoreCase) + 1), CultureInfo.InvariantCulture);
}
}
}
和你一样,数据主要存储在Contents,这是一个ExpandoObject,这就是我的问题所在。
我正在尝试做这样的事情:
var collection =
database.GetCollection<Record>("recordData").AsQueryable()
.Where(x => x.Contents.SingleOrDefault(z => z.Key == "dateOfBirth").Value.ToString().Length > 0)
.ToList();
但我得到了这个例外:
System.InvalidOperationException H结果=0x80131509 Message={document}{contents}.SingleOrDefault(z => (z.Key == "dateOfBirth")).Value.ToString().Length 不受支持。
另外,当我尝试时:
var collection1 = database.GetCollection<Record>("recordData").AsQueryable()
.Where(x => (DateTime)(x.Contents.SingleOrDefault(z => z.Key == "dateOfBirth").Value) > DateTime.Now)
.ToList();
我得到了这个例外:
System.InvalidOperationException
HResult=0x80131509
Message=Convert({document}{contents}.SingleOrDefault(z => (z.Key == "dateOfBirth")).Value) is not supported.
另外,当我这样做时:
var collection =
database.GetCollection(“recordData”).AsQueryable()
.Where(x => (DateTime)x.Contents.First(z => z.Key == “dateOfBirth”).Value > DateTime.Now ).ToList();
我遇到了这个异常:
System.NotSupportedException: ‘The expression tree is not supported: {document}{contents}’
所以我的问题实际上是如何使用 AsQueryable 和 LINQ 对 ExpandoObject 类型的对象运行查询。
谢谢!
【问题讨论】:
标签: c# mongodb linq mongodb-.net-driver