使用实体框架模拟存储库

时间:2011-03-04 14:14:15

标签: 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);
}

如果我像这样使用它,我如何为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; }
}

现在我正在使用DbSet

1 个答案:

答案 0 :(得分:2)

好吧,由于IProductsRepository实现了IEntities,你应该有一个

public DbSet<Product> Products { get; set; }
那里有

属性,但我要做的是向Fetch添加IProductRepository方法,如

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

    // New method
    IQueryable<Product> FetchAll();
}

然后,在MockProductsRepository更改设置行,如下所示:

mockProductsRepos.Setup(x => x.FetchAll()).Returns(prods.AsQueryable());