我想避免在我的应用程序中为每个模型实体创建重复的 CRUD 控制器,并追求 DRY 方法。
我正在尝试构建一个解决方案,在该解决方案中,我将通用 BaseController 创建到现有的最小 .net 7.0 Web API 中,该 API 使用 AdventureWorks 数据库和 EF 核心。
我有一个当前继承 ControllerBase 的产品控制器,但是当我尝试继承 BaseController 时,我得到 CS0311:类型“AdventureWorks2017API.Models.Product”不能用作泛型类型或方法“BaseController”中的类型参数“TEntity”
没有从“AdventureWorks2017API.Models.Product”到“AdventureWorks2017API.BaseModel”的隐式引用转换
所以,我应该通过修改 BaseController 来尝试隐式转换,还是这里的方法是错误的。
我是否应该尝试在 BaseController ControllerBase 继承以及 BaseModel 中说“TEntity 数组的位置”,同时指定我需要的所有 AdventureWorks 模型实体?
using AdventureWorks2017API.Models;
using Microsoft.AspNetCore.Mvc;
namespace AdventureWorks2017API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ProductsController : BaseController<Product> // ControllerBase
{
private readonly AdventureWorks2017Context _context;
public ProductsController(AdventureWorks2017Context context)
{
this._context = context;
}
[HttpGet("GetAllProducts")]
public List<Product> GetAllProducts()
{
return _context.Products.ToList();
}
}
}
using AdventureWorks2017API.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AdventureWorks2017API.Controllers
{
[ApiController]
public class BaseController<TEntity> : ControllerBase where TEntity: BaseModel
{
// protected readonly BaseControllerDBContext _context;
protected readonly AdventureWorks2017Context _context;
protected DbSet<TEntity> _dbSet { get; set; }
// public BaseController(BaseControllerDBContext context)
public BaseController(AdventureWorks2017Context context)
{
_context = context;
_dbSet = _context.Set<TEntity>();
}
[HttpGet]
public virtual async Task<IEnumerable<TEntity>> GetAllAsync(int count = -1, int skip = -1, string searchTerm = "", string sortBy = "")
{
if (!String.IsNullOrEmpty(searchTerm))
{
throw new Exception("Cannot search in base controller.");
}
if (!String.IsNullOrEmpty(sortBy))
{
throw new Exception("Cannot sort in base controller.");
}
if (count != -1 && skip != -1)
{
return await _dbSet.Skip(skip).Take(count).ToListAsync();
}
return await _dbSet.ToListAsync();
}
[HttpGet("{id}")]
public virtual async Task<TEntity?> GetAsync(Guid id)
{
return await _dbSet.Where(e => e.Id == id).FirstOrDefaultAsync();
}
[HttpDelete("{id}")]
public virtual async Task DeleteAsync(Guid id)
{
var entity = await _dbSet.Where(e => e.Id == id).FirstOrDefaultAsync();
if (entity != null)
{
_dbSet.Remove(entity);
}
await _context.SaveChangesAsync();
}
[HttpPost]
public virtual async Task<TEntity> CreateAsync(TEntity entity)
{
await _dbSet.AddAsync(entity);
await _context.SaveChangesAsync();
return entity;
}
[HttpPut]
public virtual async Task<TEntity> UpdateAsync(TEntity entity)
{
_dbSet.Update(entity);
await _context.SaveChangesAsync();
return entity;
}
}
}
从你的错误信息来看,这个错误信息最可能的原因是你的
Product
模型没有继承自BaseModel
模型,所以你可以检查你的Product
是否是:
public class Product: BaseModel
{
//..........
}