Unit Of Work & Generic Repository with Entity Framework 5

后端 未结 2 1850
孤城傲影
孤城傲影 2020-12-12 14:09

I\'m using ASP.NET MVC 4 with Entity Framework 5. I have model classes and Entity Maps to map existing tables to those model classes. All this is setup fine and works great.

相关标签:
2条回答
  • 2020-12-12 14:40

    Your ExampleService class is expecting IUnitOfWork, that means you just need another IUnitOfWork that is a Mock and its GetRepository() method will return an IRepository Mock.

    For example (not really a Mock but In-Memory stub):

      public InMemoryRepository<T> : IRepository<T> where T : class
      {
            ........
      }
    
      public InMemoryUnitOfWork : IUnitOfWork
      {
           public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
           {
                return new InMemoryRepository<TEntity>();
           }
      }
    

    Then:

    public IEnumerable<Example> GetAll()
    {
        // Create Unit Of Work object
        IUnitOfWork uow = new InMemoryUnitOfWork();
    
        // Create Service with Unit Of Work
        ExampleService service = new ExampleService(uow);
    
        return service.getAll();
    }
    
    0 讨论(0)
  • 2020-12-12 14:40

    You can follow the following link it is very helpful.

    Generic Repository Pattern in MVC3 Application with Entity Framework

    Entity Framework and Data Patterns

    0 讨论(0)
提交回复
热议问题