2017-02-25 87 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); 
} 
相关问题