c# - 如何使用 LINQ 的 AsQueryable() 从 MongoDB 的内部数组中获取数据?
问题描述
我无法从 MongoDB 的内部数组中获取数据。我得到错误:
BsonSerializationException: No matching creator found.
这是我在 MongoDB、查询和环境中的数据示例。
{
"Id" : 1,
"compName" : "Samsung Electronics Co.",
"symbol" : "005930-KRX",
"analyst" : [
{
"analystId" : 4,
"analystInit" : "SJ",
"analystFName" : "Steve",
"analystLName" : "Jobs",
"analystEmail" : "steve.jobs@apple.com"
}
],
"associates" : [
{
"analystId" : 7,
"analystInit" : "BG",
"analystFName" : "Bill",
"analystLName" : "Gates",
"analystEmail" : "bill.gates@microsoft.com"
},
{
"analystId" : 10,
"analystInit" : "MJ",
"analystFName" : "Michael",
"analystLName" : "Jordan",
"analystEmail" : "michael.jordan@nba.com"
}
],
"gics" : "75301020",
"cusip" : null
}
POCO
[BsonIgnoreExtraElements]
class CompanyClass
{
#region [ Properties ]
[BsonElement("issuerId")]
public Int32 IssuerId { get; set; }
[BsonElement("compName")]
public string CompName { get; set; }
[BsonElement("symbol")]
public string Symbol { get; set; }
[BsonElement("analyst")]
public IEnumerable<AnalystClass> Analyst { get; set; }
[BsonElement("associates")]
public IEnumerable<AnalystClass> Associates { get; set; }
[BsonElement("gics")]
public string Gics { get; set; }
[BsonElement("cusip")]
public string Cusip { get; set; }
#endregion
}
[BsonIgnoreExtraElements]
class AnalystClass
{
#region [ Properties ]
[BsonElement("init")]
public string ResAnInit { get; set; }
[BsonElement("firstName")]
public string ResAnFirstName { get; set; }
[BsonElement("lastName")]
public string ResAnLastName { get; set; }
[BsonElement("email")]
public string ResAnEmail { get; set; }
#endregion
}
询问:
compCollection = GetMonDB("Companies").GetCollection<CompanyClass>("coverage");
var comps = compCollection.AsQueryable()
.Select(c => new {
CompName = c.CompName,
Symbol = c.Symbol,
ResAnsFName = c.Analyst.Select(x => x.ResAnFirstName) <-- Problem line
CUSIP = c.Cusip
});
我想得到这个:
我的环境:
C# MongoDB.Driver = 2.12
MongoDB = 4.2
Windows = Win10
看来我错过了一些明显的东西。我究竟做错了什么?
解决方案
只需像这样进行投影:
var comps = await compCollection
.AsQueryable()
.Select(c => new
{
...
ResAnsFName = c.Analyst.first().ResAnFirstName
...
})
.ToListAsync();
推荐阅读
- api - 如何在 openweather API 中找到 7 天的天气预报?
- android - 在android中执行顺序任务问题
- glsl - 通过制服打破 GLSL 循环
- c# - 在c#中使用显示格式删除逗号
- javascript - 在nodeJS中使用多个字段自动完成搜索
- iis - 发生指定错误日志时如何自动回收应用程序池?
- java - RecyclerView 在整个 View 中只显示一个值
- javascript - 如何通过 pubsub 在 shell 应用程序和微应用程序(前端)之间安全通信
- python - 将第一段从 infile 打印到 outfile
- java - 将格式错误的 JSON 列表解析为对象:使用 Java 解析的最佳实践