【问题标题】:Mapping C# object to BsonDocument将 C# 对象映射到 BsonDocument
【发布时间】:2016-07-04 17:59:45
【问题描述】:

我对 MongoDB 比较陌生。我有一个具有以下定义的对象

[BsonDiscriminator("user")]
public Class BrdUser
{
    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    public string ID { get; set; }

    [BsonElement("username")]
    public string UserNm { get; set; }

    [BsonElement("email")]
    public string EmailAdrs { get; set; }
    .
    .
    .
    public IList<Question> Questions{ get; set; } //<-- Un sure as to what Bson type should this be
}

Questions 是另一个 BsonDocument 定义为:

[BsonDiscriminator("userques")]
public class Question
{
    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    public string ID { get; set; }

    [BsonElement("title")]
    public string Title{ get; set; }

    [BsonElement("desc")]
    public string Desciption{ get; set; }
}

我的问题是在映射时,我应该使用什么属性以便用户对象与问题对象反序列化。 C#驱动中没有[BsonDocument]属性。

【问题讨论】:

  • 你试过序列化对象吗?结果是什么?
  • 我的问题是赋予 IList 什么属性

标签: c# asp.net-mvc mongodb mapping


【解决方案1】:

我不确定你在哪里卡住了,但试试:

var brdDoc = new BrdUser ();
brdDoc.UserNm = "invisible";
brdDoc.EmailAdrs = "someone@womewhere.com";
brdDoc.Questions = new []{ new Question{ Title = "Q", Desciption = "Question to ask" } };

var bsonDocument = brdDoc.ToBsonDocument ();
var jsonDocument = bsonDocument.ToJson ();

Console.WriteLine (jsonDocument);

它将打印:

{ 
   "_id" : null, 
   "username" : "invisible", 
   "email" : "someone@womewhere.com", 
   "Questions" : [{ "_id" : null, "title" : "Q", "desc" : "Question to ask" }] 
}

【讨论】:

  • 抱歉回复晚了,我的问题是问题列表的属性是什么?会是 [BsonElement] 还是别的什么?
  • 你不必使用属性。试一试。
猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2012-04-16
  • 2010-09-10
  • 1970-01-01
相关资源
最近更新 更多