我是mongodb的新手,我正在为一个新项目开发mvc4 web应用程序.
我想使用将与mongodb上下文进行数据库级通信的存储库模式.
我与Entity Framework 4.0一起使用的简单界面如下.发现成员对我来说是个问题.我不知道如何使用mongodb上下文继续它们.
public interface IRepository<T> where T : class
{
void Add(T entity);
void Remove(T entity);
IQueryable<T> Find(Expression<Func<T, bool>> predicate);
//IQueryable<T> FindAll();
}
我有一个非常简单的模型叫做Hero,它的驱动程序来自ImongoEntity,它提供了一个名为accessId的成员.
public class Hero : MongoDB.Kennedy.IMongoEntity
{
public ObjectId _id { get; set; }
public string Name { get; set; }
public string Alias { get; set; }
public string _accessId { get; set;}
}
Context类很简单,你可以看到Heros的集合被公开为IQueryable属性.
public class MongoDataConetext: MongoDB.Kennedy.ConcurrentDataContext
{
public MongoDataConetext(string databaseName, string serverName="localhost") : base(databaseName, serverName)
{
}
public IQueryable<Hero> Heros {
get {
return base.GetCollection<Hero>().AsQueryable();
}
}
}
现在在我的存储库中,大多数简单的方法都是添加和删除它们成功地与mongodb上下文对话并从mongodb中添加或删除实体.然而,Find方法给出了编译器级错误.我的发现需要帮助,找到所有方法.我正在使用genrics,因为我需要我的repositry类,用于英雄,解决方案,项目,用户和类别.
public class Repository<T> : IRepository<T> where T : class, IMongoEntity
{
private readonly MongoDataConetext _ctx;
public Repository(MongoDataConetext ctx)
{
_ctx = ctx;
}
public void Add(T entity)
{
_ctx.Save(entity);
}
public void Remove(T entity)
{
_ctx.Delete(entity);
}
public IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
_ctx.Heros.Where(predicate);
//throw new NotImplementedException();
}
//public IQueryable<T> FindAll()
//{
// throw new NotImplementedException();
//}
}
解决方法:
如果您对类似于Rob Connery和NBlog存储代码的实现感兴趣,但使用mongodb csharp驱动程序2.0(即异步),您可以查看:
https://github.com/alexandre-spieser/mongodb-generic-repository
然后,您可以编写从BaseMongoRepository继承的自定义存储库.
public interface ITestRepository : IBaseMongoRepository
{
void DropTestCollection<TDocument>();
void DropTestCollection<TDocument>(string partitionKey);
}
public class TestRepository : BaseMongoRepository, ITestRepository
{
public TestRepository(string connectionString, string databaseName) : base(connectionString, databaseName)
{
}
public void DropTestCollection<TDocument>()
{
MongoDbContext.DropCollection<TDocument>();
}
public void DropTestCollection<TDocument>(string partitionKey)
{
MongoDbContext.DropCollection<TDocument>(partitionKey);
}
}
更新:它现在作为自己的nuget包提供:
Install-Package MongoDbGenericRepository
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。