使用MongoDB的存储库模式:在何处初始化数据库

时间:2011-04-10 11:17:31

标签: c# mongodb repository-pattern

我刚刚开始使用MongoDB(C#)并尝试从实体框架移植存储库。我正在使用官方的C#驱动程序1.0。现在我做了这样的事情:

internal class MongoContext
{
    public MongoContext(string constring)
    {
        MongoServer server = MongoServer.Create(constring);
        this.myDB = server.GetDatabase("MyDB");

        BsonClassMap.RegisterClassMap<VoyageNumber>(cm =>
            { cm.MapField<string>(p => p.Id); });
        BsonClassMap.RegisterClassMap<Schedule>(cm =>
        { cm.MapField<DateTime>(p => p.EndDate); cm.MapField<DateTime>(p => p.StartDate); });
        BsonClassMap.RegisterClassMap<Voyage>(cm =>
            { cm.MapIdField<VoyageNumber>(p => p.VoyageNumber); cm.MapField<Schedule>(p => p.Schedule); });

    }

    private MongoDatabase myDB;
    public MongoDatabase MyDB
    { get { return this.myDB; } }
}

然后我继续这样实现Repository:

public class MongoVoyageRepository : IVoyageRepository
{
    private readonly MongoContext context;

    public MongoVoyageRepository(string constring)
    {
        this.context = new MongoContext(constring);
    }

    public void Store(Domain.Model.Voyages.Voyage voyage)
    {

        MongoCollection<Voyage> mongoVoyages = context.MyDB.GetCollection<Voyage>("Voyages");

        //store logic...

    }

}

现在我想知道在性能方面实例化这样的“上下文”是否是一个好的决定。把BsonClass地图放在那里是否有意义? 感谢您的投入。

3 个答案:

答案 0 :(得分:11)

// entity base
public class MongoEntity {
    public ObjectId _id { get; set; }
}

//user entity
public class Users : MongoEntity {
    public string UserName { get; set; }
    public string Password { get; set; }
}


// simple repository
public class Repository {

    private MongoDatabase _db;
    public MongoDatabase Database { get; private set; }
    public Repository(string constr, string dbname) {
        var server = MongoServer.Create(constr);
        _db = server.GetDatabase(dbname);
        Database = _db;
    }

    private MongoCollection<T> GetCollection<T>() where T : MongoEntity {
        return _db.GetCollection<T>(typeof(T).Name);
    }

    public IEnumerable<T> List<T>() where T : MongoEntity {
        return GetCollection<T>().FindAll();
    }

    public IEnumerable<T> List<T>(Expression<Func<T, bool>> exp) where T : MongoEntity {
        return GetCollection<T>().AsQueryable<T>().Where(exp);
    }

    public T Single<T>(Expression<Func<T, bool>> exp) where T : MongoEntity {
        return List<T>(exp).SingleOrDefault();
    }

    public void Insert<T>(T entity) where T : MongoEntity {
        GetCollection<T>().Insert<T>(entity);
    }

    public void Insert<T>(ICollection<T> entities) where T : MongoEntity {
        GetCollection<T>().InsertBatch(entities);
    }

    // Update, Delete method etc ...



}



// example
var repository = new Repository("mongodb://localhost", "test");
repository.Single<Users>(u => u.UserName == "myUserName");

答案 1 :(得分:2)

我想每次创建存储库类时注册类映射都没有意义。由于MongoDB C#驱动程序在内部管理与MongoDB的连接,因此在我看来,最好在应用程序启动期间创建MongoServer并注册类映射一次,然后再使用它。

我正在使用单身人士才能创建MongoServer一次

public class MongoRead : MongoBase
{
  public MongoRead(MongoServer server)
            : base(server)
  {

  }


  public override MongoDatabase Database
  {
     get { return Server.GetDatabase("myDb"); }
  }

  public MongoCollection Logs
  {
    get { return Database.GetCollection("logs"); }
  }

  private static MongoRead _instance = null;

  public static MongoRead Instance
  {
    get
      {
        if (_instance == null)
        {
          _instance = RegisterMongoDb();

        }

        return _instance;
      }

  }

  private static MongoRead RegisterMongoDb()
  {
      var readServer = MongoServer.Create(connectionString);
      var read = new MongoRead(readServer);

      var myConventions = new ConventionProfile();
      myConventions.SetIdMemberConvention(new NoDefaultPropertyIdConvention());
      BsonClassMap.RegisterConventions(myConventions, t => true);

      return read;
  }

}

所以你也可以在你的Repository中使用上面的类:

public class MongoVoyageRepository : IVoyageRepository
{
    private readonly MongoRead context
    {
      get { return MongoRead.Instance; }
    };

    public MongoVoyageRepository()
    {
    }

    public void Store(Domain.Model.Voyages.Voyage voyage)
    {
            MongoCollection<Voyage> mongoVoyages = 
                  context.Database.GetCollection<Voyage>("Voyages");
            //store logic...
    }

}

答案 2 :(得分:0)

如果你想使用存储库模式,

this也很有意思。