首页 > 解决方案 > MongoDB 驱动程序不插入列表C# 模型的属性作为数组

问题描述

我有一个具有List<string>属性的模型:

public class SignalDoc_Header_NamedMeasures
{
    public ObjectId Id { get; set; }
    public string Type { get; set; }
    public string SignalName { get; set; }
    public string Filename { get; set; }
    public DateTime DateStart { get; set; }
    public DateTime DateEnd { get; set; }
    public List<string> HeaderLines{ get; }

    public SignalDoc_Header_NamedMeasures()
    {
        HeaderLines = new List<string>();
    }
}

数据文件解析器将填充模型并将其存储在集合中

var dataHeader = new SignalDoc_Header_NamedMeasures
{
    Type = "Foo",
    SignalName = "xyzzy",
    Filename = fi.FullName,
};
…
// read through top part of a tricky text file to header line section
dataHeader.HeaderLines.Add(line);  // save the header line, other files might have multiple header lines.
… 
// parse file, tracking first and last timestamp of detail records
… 
dataHeader.DateStart = dateStart;
dataHeader.DateEnd = dateEnd;
… 

string collectionName = … some function of filename … ;
DropCollection(collectionName); // helper method

var h = AppDb.GetCollection<SignalDoc_Header_NamedMeasures>(collectionName);
await h.InsertOneAsync(dataHeader);

有效,但插入的InsertOneAsync文档不包含HeaderLines. 我使用 Compass Community 来查看数据库。

问:缺少什么或阻止将List<string>其存储为 Array ?

在其他地方,AppDb建立为

    static MongoClient Client { get; set; }
    static IMongoDatabase AppDb { get; set; }

    static async Task<int> Main(string[] args)
    {
        try {
            Client = new MongoClient($"mongodb://{ConnectionParameters}");
        } catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Environment.Exit(-1);
        }

        AppDb = Client.GetDatabase(DatabaseName);

标签: c#mongodb-.net-driver

解决方案


事实证明,该属性set还需要一个默认值,以便 MongoDB 驱动程序“尊重”它。

public List<string> HeaderLines { get; }        // driver does not store
public List<string> HeaderLines { get; set; }   // driver stores as Array

推荐阅读