Temukan cara menyimpan data ke MongoDB di sini:Konversi Kamus-ke-BsonDocument menghilangkan bidang _t dan memperluasnya sedikit, jadi saya berpikir untuk membagikan solusi lengkapnya.
Langkah #1:
Di kelas saya, saya mendeklarasikan 2 anggota untuk setiap nilai:
// For the Hobbies object type:
[BsonIgnore] //ignore this value in MongoDB
public Dictionary<string, object> Hobbies { get; set; }
[JsonIgnore] //ignore this value in the response on Get requests
[BsonElement(elementName: "Hobbies")]
public BsonDocument HobbiesBson { get; set; }
/*********************************************************************/
// For the Collection object type:
[BsonIgnore] //ignore this value in MongoDB
public List<Dictionary<string, object>> Collection { get; set; }
[JsonIgnore] //ignore this value in the response on Get requests
[BsonElement(elementName: "Collection")]
public BsonArray CollectionBson { get; set; }
Langkah #2
Dalam metode pengontrol WebAPI saya untuk Post
[HttpPost]
public override async Task<IActionResult> Post([FromBody] Person person)
{
var jsonDoc = JsonConvert.SerializeObject(person.Hobbies);
person.HobbiesBson = BsonSerializer.Deserialize<BsonDocument>(jsonDoc);
jsonDoc = JsonConvert.SerializeObject(person.Collection);
person.CollectionBson = BsonSerializer.Deserialize<BsonArray>(jsonDoc);
//save
}
Langkah #3
Di Get
. saya minta saya deserialize kembali seperti ini:
[HttpGet("{id?}")]
public override async Task<IActionResult> Get(string id = null)
{
var people = //get data from mongoDB
foreach (var person in people)
{
var bsonDoc = BsonExtensionMethods.ToJson(person.HobbiesBson);
person.Hobbies = JsonConvert.DeserializeObject<Dictionary<string, object>>(bsonDoc);
bsonDoc = BsonExtensionMethods.ToJson(person.CollectionBson);
person.Collection = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(bsonDoc);bsonDoc);
}
return Ok(people);
}
Ini memecahkan masalah saya dan saya harap ini dapat membantu orang lain juga :-)