【发布时间】:2011-03-31 15:06:45
【问题描述】:
我有以下课程:
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 对象的集合,因为存储库不知道我提供什么类型直到运行时。 - 我需要为 Query() 方法支持 LINQ to Objects。假设我能想出一个体面的方法来存储对象,这应该像返回存储对象数组 AsQueryable() 一样简单。
您将如何存储对象以满足上述要求?
【问题讨论】:
-
GetAll<T>(queryName)- 你能提供更多信息吗?对象本身呢?它们是否实现了某种唯一标识它们的方法?是否需要考虑层次结构/关系/图表? -
对于此类,请忽略该方法。该方法用于运行返回结果的存储过程(NHibernate 术语中的“命名查询”),而不是直接查询表。
标签: c# design-patterns