简体   繁体   English

将Automapper与泛型一起使用

[英]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. 我有一个基类存储库,它包含从中继承的一组类的基本功能,例如UserRepository或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. GetUserByNTId将起作用,因为我可以在return语句中使用自动映射器。 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. 但是Get不能使用,因为它处理TEntity而且我不知道如何告诉自动映射器检查TEntity的类型并查找匹配的映射。

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? 如何更改Get函数的return语句,以使其对我的所有派生存储库都有效,并且仍然使用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? 还是只需要接受所有通用功能并将其推入派生类并消除Repository基类?

It's a very bad idea to for mixing AutoMapper and other responsibilities when querying from a Repository pattern . 存储库模式查询时,混合使用AutoMapper和其他职责是一个非常糟糕的主意。 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));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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