我有以下课程:
public class InMemoryRepository : IRepository
{
public void Add(object entity)
{
throw new NotImplementedException();
}
public void Attach(object Entity)
{
throw new NotImplementedException();
}
public T Get<T>(object id)
{
throw new NotImplementedException();
}
public IList<T> GetAll<T>(string queryName)
{
throw new NotImplementedException();
}
public IList<T> GetAll<T>()
{
throw new NotImplementedException();
}
public IQueryable<T> Query<T>()
{
throw new NotImplementedException();
}
public void Remove(object entity)
{
throw new NotImplementedException();
}
public void Save(object entity)
{
throw new NotImplementedException();
}
}
我们的默认存储库实现使用 NHibernate 作为后备存储,但我想实现它的内存版本,这样我就可以对域对象进行原型设计,而无需创建后备 SQL 数据库。假设所有对象都有一个 Id 属性作为主键,您将如何为此实现通用内存存储?
我很难解决一些关键点:
- 存储库方法本身是通用的,因此我需要某种机制来自动存储和引用不同类型。
Get<TestEntity>(object id)
应该能够查询 TestEntity 的所有存储实例并找到具有匹配 Id 属性的实例,但我无法直接定义 TestEntity 对象的集合,因为存储库直到运行时才知道我要为其提供什么类型。
- 我需要支持 LINQ to Objects 的 Query() 方法。假设我可以想出一种存储对象的好方法,这应该像返回存储对象的数组 AsQueryable() 一样简单。
您将如何存储对象来满足上述要求?
基础知识很简单:
public class InMemoryRepository : IRepository
{
private readonly IList<object> entities = new List<object>();
public T Get<T>(object id)
{
return entities.OfType<T>.SingleOrDefault(e => e.ID == id);
}
public IList<T> GetAll<T>()
{
return entities.OfType<T>.ToList();
}
public IQueryable<T> Query<T>()
{
return GetAll<T>.AsQueryable();
}
}
然而,一旦涉及到public IList<T> GetAll<T>(string queryName)
,事情变得复杂了。
您可能可以使用基于 SQLite 的存储库实现来进行测试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)