使用类继承的文档中的重复元素

时间:2019-01-18 01:18:31

标签: c# mongodb nosql

我在我的应用程序中使用了C#的MongDB驱动程序2.7.2(服务器4.0.5),并尝试插入此模型:

abstract class ModelBase
{
    public virtual int Duration { get; set; }
    public virtual DateTime EndDate { get; set; }
    public virtual DateTime StartDate { get; set; }
}

class MongoModel : ModelBase
{

   [BsonElement("_id")]
   public ObjectId Id { get; set; }

   [BsonElement("duration")]
   public override int Duration { get; set; }

   [BsonElement("end_date")]
   public override DateTime EndDate { get; set; }

   [BsonElement("start_date")]
   public override DateTime StartDate { get; set; }
}

我使用此类继承是因为我希望能够创建MongoBase(MongoDB),DynamoBase(AWS)等

但是,当插入时,将显示下一个文档(具有重复的元素):

class MongoDBDataProvider : DataProvider
{
    private MongoClient _client;
    public MongoDBDataProvider(string endpoint) : base(endpoint)
    {
        _connectionString = $"mongodb://{_endpoint}";
        _client = new MongoClient(_connectionString);
    }


    public override async Task Insert(ModelBase src)
    {
        var coll = GetCollection();
        await coll.InsertOneAsync((MongoModel)src);
    }

    private IMongoCollection<MongoModel> GetCollection()
    {
        IMongoDatabase db = _client.GetDatabase("db");
        return db.GetCollection<MongoModel>("coll");
    }
}

结果:

_id:5c4123116b2940340551785f
Duration:10
EndDate:2020-02-02 05:02:00.000
StartDate:2020-02-02 05:02:00.000
duration:10
end_date:2020-02-02 05:02:00.000
start_date:2020-02-02 05:02:00.000

为什么会这样?有什么提示吗?我在做什么错了?

1 个答案:

答案 0 :(得分:0)

使用BsonIgnore属性忽略属性

public interface ModelBase
{
    int Duration { get; set; }
    DateTime EndDate { get; set; }
    DateTime StartDate { get; set; }
}