使用实体框架模拟存储库

Dav*_*rák 6 entity-framework moq

我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)

如果我像这样使用它,我如何为Entity框架更改此函数:

public interface IProductsRepository : IEntities{
    EntityState GetEntryState(object entry);
    void SetEntryState(object entry, EntityState state);
    void Commit();
}

public interface IEntities{
    DbSet<Product> Products { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在我正在使用DbSet.

Ser*_*eit 2

好吧,既然IProductsRepository实现了,IEntities你应该有一个

public DbSet<Product> Products { get; set; }
Run Code Online (Sandbox Code Playgroud)

那里有属性,但我要做的是添加一个Fetch方法来IProductRepository喜欢

public interface IProductsRepository : IEntities
{
    EntityState GetEntryState(object entry);
    void SetEntryState(object entry, EntityState state);
    void Commit();

    // New method
    IQueryable<Product> FetchAll();
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的MockProductsRepository设置行中进行如下更改:

mockProductsRepos.Setup(x => x.FetchAll()).Returns(prods.AsQueryable());
Run Code Online (Sandbox Code Playgroud)