我有这个树接口/类
BaseRepository.cs
abstract public class BaseRepository<Entity> : IRepository
where Entity : BaseEntity, new()
{
public virtual IList<Entity> FindAll()
{
...
return list;
}
}
尝试使用泛型自动化Get,Update,Insert webapi
BaseApiController
public class BaseEntityApiController<Repository> : ApiController
where Repository : BaseRepository<BaseEntity>, new()
{
Repository repository = new Repository();
public IList<BaseEntity> Get()
{
return repository.FindAll();
}
}
UserRepository
public class UserRepository : BaseRepository<User>
{
}
我创建了一个新的控制器,它从BaseApiController继承传递UserRepository:
UserController中
public class UserController : BaseApiController<UserRepository>
{
}
我收到此错误:
Project.UserRepository cannot be used as type parameters 'Repository' in the generic type or method 'BaseApiController<Repository>'. There is no implicit reference conversion from Project.UserRepository to Project BaseRepository<Project.BaseEntity>.
如何将带有泛型类型的UserRepository传递给我的BaseApiController,以自动创建所有控制器中使用的Api?
答案 0 :(得分:1)
将实体类型的泛型类型参数添加到BaseEntityApiController
定义:
public class BaseEntityApiController<TRepository, TEntity> : ApiController
where TRepository : BaseRepository<TEntity>, new()
where TEntity : BaseEntity, new()
{
// ...
}
答案 1 :(得分:0)
确保:
public class User: BaseEntity
{
}
你可能也想要一个双重通用:
public class BaseEntityApiController<Repository, BaseEntity> : ApiController
where Repository : BaseRepository<BaseEntity>, new()
{
Repository repository = new Repository();
public IList<BaseEntity> Get()
{
return repository.FindAll();
}
}
这样你就不必像以下那样投射:
UserController.Get().Cast<User>()
只是这样做:
public class UserController : BaseEntityApiController<UserRepository, User>{}
UserController.Get()
一次双重定义泛型与不断从BaseEntity转换为用户