将新项目动态添加到 IQueryable 硬编码假存储库
在使用真正的数据库之前构建应用程序,为了让事情正常工作,我可以首先使用硬编码列表作为假的内存存储库:
public class FakeProductsRepository
{
private static IQueryable<Product> fakeProducts = new List<Product> {
new Product{ ProductID = "xxx", Description = "xxx", Price = 1000},
new Product{ ProductID = "yyy", Description = "xxx", Price = 2000},
new Product{ ProductID = "zzz", Description = "xxx", Price = 3000}
}.AsQueryable();
public IQueryable<Product> Products
{
get { return fakeProducts; }
}
}
如何向此类添加方法以添加新的非硬编码项目动态地在此列表中?
Building an application, before using a real database, just to get things work I can first use a hard-coded list as a fake, in-memory repository:
public class FakeProductsRepository
{
private static IQueryable<Product> fakeProducts = new List<Product> {
new Product{ ProductID = "xxx", Description = "xxx", Price = 1000},
new Product{ ProductID = "yyy", Description = "xxx", Price = 2000},
new Product{ ProductID = "zzz", Description = "xxx", Price = 3000}
}.AsQueryable();
public IQueryable<Product> Products
{
get { return fakeProducts; }
}
}
How to add a method to this class for adding new, not hard-coded items in this list dynamically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需保留列表<产品>即可在 List类型的字段中而不是 IQueryable:
Just keep the List<Product> in a field of type List<Product> instead of IQueryable<Product>:
如果您打算模拟您的存储库以进行测试,那么我建议您首先声明一个包含您期望从存储库中获得的功能的接口。然后构建真实的和“假的”存储库来实现该接口,否则您将无法轻松地用一个存储库替换另一个存储库。
一旦有了一致的接口,你就会发现这很容易,函数已经被声明了,即
If you are going to Mock your repository for testing purposes then I'd suggest that you start by declaring an interface that encompasses the functions your expect from your repository. Then build your real and your 'fake' repository to implement that interface, otherwise you won't be able to easily substitute one for the other.
You'll find it pretty easy once you have that consistent interface, the functions will already be declared, i.e.