使用实体框架模拟存储库
我使用 mog 来模拟具有 LINQ to SQL 的存储库,如下所示:
public static IProductsRepository MockProductsRepository(params Product[] prods){
// Generate an implementer of IProductsRepository at runtime using Moq
var mockProductsRepos = new Mock<IProductsRepository>();
mockProductsRepos.Setup(x => x.Products).Returns(prods.AsQueryable());
return mockProductsRepos.Object;
}
public interface IProductsRepository{
IQueryable<Product> Products { get; }
void SaveProduct(Product product);
void DeleteProduct(Product product);
}
如果我像这样使用它,如何更改实体框架的此函数:
public interface IProductsRepository : IEntities{
EntityState GetEntryState(object entry);
void SetEntryState(object entry, EntityState state);
void Commit();
}
public interface IEntities{
DbSet<Product> Products { get; set; }
}
现在我正在使用 DbSet
。
I'm using mog for mocking a repository with LINQ to SQL like this:
public static IProductsRepository MockProductsRepository(params Product[] prods){
// Generate an implementer of IProductsRepository at runtime using Moq
var mockProductsRepos = new Mock<IProductsRepository>();
mockProductsRepos.Setup(x => x.Products).Returns(prods.AsQueryable());
return mockProductsRepos.Object;
}
public interface IProductsRepository{
IQueryable<Product> Products { get; }
void SaveProduct(Product product);
void DeleteProduct(Product product);
}
How can I change this function for the Entity framework if I am using it like this:
public interface IProductsRepository : IEntities{
EntityState GetEntryState(object entry);
void SetEntryState(object entry, EntityState state);
void Commit();
}
public interface IEntities{
DbSet<Product> Products { get; set; }
}
Now I am using DbSet
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,由于
IProductsRepository
实现了IEtities
,你应该在其中有一个属性,但我要做的就是向
IProductRepository 添加一个
就像Fetch
方法然后,在您的
MockProductsRepository
中更改设置行,如下所示:Well, Since
IProductsRepository
implementsIEntities
you should have aproperty in there, but what I would do is add a
Fetch
method toIProductRepository
likeThen, in your
MockProductsRepository
change the setup line as follows: