gpt4 book ai didi

c# - MongoDB 的存储库模式 : Where to initialize the Database

转载 作者:太空狗 更新时间:2023-10-29 17:47:11 26 4
gpt4 key购买 nike

我刚开始使用 MongoDB (C#) 并尝试从 Entity Framework 移植一个存储库。我正在使用官方 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; } }
}

然后我会继续像这样实现存储库:

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 映射放在那里有意义吗?感谢您的输入。

最佳答案

// 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");

关于c# - MongoDB 的存储库模式 : Where to initialize the Database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5611383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com