gpt4 book ai didi

c# - 多个数据提供者/ORM 上的存储库模式?

转载 作者:太空狗 更新时间:2023-10-30 01:09:30 24 4
gpt4 key购买 nike

假设我有以下数据模型:

public class Account
{
public string Username { get; set; }
public string Password { get; set; }
}

public class Configuration
{
public string Key { get; set; }
public string Value { get; set; }
}

目前,它们每个都有自己的数据访问存储库,并使用 Entity Framework 作为其工作单元/DbContext。我打算将配置部分从 Entity Framework 中拉出来,并使用 Redis 或 Memcached 作为其数据访问。我什至可能将 EF 切换到 NHibernate 或根本不使用 ORM,并且我可能将数据库切换到 MongoDB 或 CouchDB。

这样做的好方法是什么?对我的业务逻辑中所有那些较低层的东西一无所知?使用什么样的模式?为这样的变化而设计是可能的还是坏事?

谢谢:)

最佳答案

如前一篇文章所述,您应该走“界面之路”。我个人并不直接为每个 orm 实现存储库,但我使用了一些变体。使用您的示例...

public interface IAccountRepository
{
Account Get(int id);
void Delete(int id);
...other method...
}

然后你创建你的仓库

public class AccountRepository : IAccountRepository
{
private readonly IUnitofWork unitofWork;

public AccountRepository(IUnitofWork unitofWork)
{
this.unitofWork = unitofWork;
}

//Implement interface method
public Account Get(int id)
{
//some logic or just the call to the unit of work
return unitofWork.Get(id);
}
}

我对这个解决方案很满意,因为我最终只有一个存储库,90% 的时间使用 linq 进行查询,所以我不必为每个工作单元编写 sql,每次我都必须编写一个带分页的“GetAllProducts” 我不必为每个工作单元编写相同的代码(和测试),而只需为我的存储库编写。这显然是一个简单的例子,所以我希望你能理解。您可以创建一个 RepositoryBase 来实现使用 linq 的 Find() 或 Query() 方法。然后使用您的 CaSTLe Windsor 或 ninject 或任何您可以注入(inject)您喜欢的工作单元。希望对您有所帮助。

更新:实现 nhibernate 的我的 UnitofWorkBase 示例是类似的:

public class NHUnitofWork<T> : IUnitofWork<T> where T : EntityBase
{
protected INHSessionBuilder SessionBuilder { get; private set; }

public NHPersistorBase(INHSessionBuilder sessionBuilder)
{
SessionBuilder = sessionBuilder;
}

public T Get(int id)
{
T result = null;
ISession session = SessionBuilder.GetSession();
using (ITransaction transaction = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
{
try
{
result = (T)session.Get(typeof(T), id);
transaction.Commit();
}
finally
{
if (transaction.IsActive)
transaction.Rollback();
}
}
return result;
}
public IQueryable<T> Find()
{
return SessionBuilder.GetSession().Query<T>();
}

关于c# - 多个数据提供者/ORM 上的存储库模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6620469/

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