Search code examples
c#.netmongodbmongodb-.net-driver

Type argument 'MongoDB.Bson.ObjectId' violates the constraint of type parameter 'TTarget'


I am trying to build a MVC website with MongoDB. I am a newbie with MongoDB. When I try to insert a new data into a collection, it throws the error below

Type argument 'MongoDB.Bson.ObjectId' violates the constraint of type parameter 'TTarget'.

My code for inserting like below...

public void Add<T>(T item) where T : class, new()
{
    _db.GetCollection<T>().Save(item);
}

My IEntity interface is like below

public interface IEntity
{
    [BsonId]
    ObjectId Id { get; set; }
    DateTime CreatedDate { get; set; }
    DateTime LastModifiedDate { get; set; }
    int UserId { get; set; }
    bool IsActive { get; set; }
    bool IsDelete { get; set; }
}

My Entity class is like below

public class Entity : IEntity
{
    [BsonId]
    public ObjectId Id { get; set; }

    public DateTime CreatedDate { get; set; }

    public DateTime LastModifiedDate { get; set; }

    public int UserId { get; set; }

    public bool IsActive { get; set; }

    public bool IsDelete { get; set; }
}

and this is the code that calls inserting...

IBusinessArticle businessArticle = new BusinessArticle();
businessArticle.Add(new Article { Title = "Test MongoDB", Body = "Body Body Body Body Body Body" });

Why does it give an error about violating the constraint. I dont get it. Please help...


Solution

  • if you insert new item, you shouldn't call Save, you should call InsertOne:

    public void Add<T>(T item) where T : class, new()
    {
        _db.GetCollection<T>().InsertOne(item);
    }