2017-02-25 135 views
1

我想用MongoDB建立一個MVC網站。我是MongoDB的新手。當我嘗試向集合中插入新數據時,它會拋出以下錯誤類型參數'MongoDB.Bson.ObjectId'違反了類型參數'TTarget'的約束

類型參數'MongoDB.Bson.ObjectId'違反了類型參數'TTarget'的約束。

我插入類似下面的代碼...

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

我IEntity界面中,就像下面

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; } 
} 

我的實體類是像下面

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; } 
} 

這是要求插入的代碼...

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

爲什麼它給出關於違反約束的錯誤。我沒有明白。請幫助...

回答

2

如果插入新的項目,你不應該叫Save,你應該叫InsertOne

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