简体   繁体   中英

Using Automapper with generics

I have a base class Repository which contains base functionality for a set of classes that inherit from it such as UserRepository or DepartmentRepository.

I'm using automapper to map between my entity framework objects and my domain objects.

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class {
    protected readonly DbContext Context;

    public Repository(DbContext context) {
        Context = context;
    }

    public TEntity Get(int id) {
        return Context.Set<TEntity>().Find(id);
    }
}

public class UserRepository : Repository<User>, IUserRepository {
    public UserRepository(DbContext context) : base(context) {
    }

    public User GetUserByNTId(string NTId) {
        return Mapper.Map<User>(DbContext.Users.SingleOrDefault(u => u.NTId == NTId));
    }

}

GetUserByNTId will work because I can use automapper in the return statement. But Get will not work because it deals with TEntity and I don't know how you can tell automapper to examine the type of TEntity and look for a matching mapping.

How can I change the return statement of the Get function so that it will work for all my derived repositories and still use automapper? Or do I just have to take all my general functions and push them down into the derived classes and eliminate the Repository base class?

It's a very bad idea to for mixing AutoMapper and other responsibilities when querying from a Repository pattern . It's also of course a violation of the Single Responsibility Principle .

A naive non tested implementation will be:

public class ExampleOfGenericRepository<TEntity> : Repository<TEntity>
    where TEntity : class
{
    public ExampleOfGenericRepository(DbContext context)
        : base(context)
    {
    }

    public TEntity GetById(int id)
    {
        return Mapper.Map<TEntity>(Get(id));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM