[英]Getting dynamic object instead of strong typed from MongoDB in .net core c#
我尝试将 MongoDB 与 .net 内核(c#)结合使用来保存一些调查结果。
挑战在于我计划使其尽可能通用,以便以后能够添加其他评级控件。
我能够在一张表中保存不同的结果类型。
public class VoteBase
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public User User { get; set; }
public Control Control { get; set; }
public string ControlType { get; set; }
}
public class VoteStarRatingControl : VoteBase
{
public int? Rating { get; set; }
}
public class VoteStarRatingWithComment : VoteStarRatingControl
{
public string Comment { get; set; }
}
我创建了一个基本类型为 MongoCollection 的表:
private readonly IMongoCollection<VoteBase> _voteBases;
为了将其保存到该集合,我使用了以下代码(其中 DTO 是相同的内容数据传输 object 以将 REST 服务与 DB 结构分离):
List<VoteBase> dbVotes = new List<VoteBase>();
foreach (VoteBaseDTO v in votes)
{
switch (v) {
case VoteStarRatingWithCommentDTO src:
dbVotes.Add(new VoteStarRatingWithComment() { User = new User() { Id = UserId }, Control = new Control() { Id = src.ControlId }, Rating = src.Rating, Comment = src.Comment });
break;
case VoteStarRatingControlDTO sr:
dbVotes.Add(new VoteStarRatingControl() { User = new User() { Id = UserId }, Control = new Control() { Id = sr.ControlId }, Rating = sr.Rating });
break;
}
}
_voteBases.InsertMany(dbVotes);
return dbVotes;
直到这里一切正常。
现在,我尝试为特定的控件列表(针对一项调查)收回选票。
以下命令失败
'元素'评级'与 class SurveyToolRestAPI.Models.VoteBase 的任何字段或属性都不匹配。
object obj = _voteBases.Find(vb => vb.Control.Id == "5e9c24c50a099728b027e176").SingleOrDefault();
这是因为它是 StarRatingControl 类型而不是 VoteBase 类型。
有没有办法从 MongoDB 集合中获取动态列表而不是强类型列表?
谢谢Eldho,您为我指明了正确的方向。
使用 Bson 进行更多研究...属性我最终在这篇文章Mongodb 集合中找到了解决方案作为动态
关键是添加一个 BsonKnownTypes 属性。 它可以用作强类型集合,并且列表将包含适当的子类型。
[BsonKnownTypes(typeof(VoteBase), typeof(VoteStarRatingControl), typeof(VoteStarRatingWithComment))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.