I created a controller with generic TEntity and TModel so that i will not have to repeat common actions like save/delete for each entity. I just want to ask if this is a good or a bad practice?
public class BaseController<TEntity, TModel> : Controller
where TEntity : BaseEntity
where TModel : BaseModel
{
private readonly IMapper _mapper;
private readonly IRepository<TEntity> _repository;
private readonly IUnitOfWork _uow;
public BaseController(
IMapper mapper,
IRepository<TEntity> repository,
IUnitOfWork uow)
{
_mapper = mapper;
_repository = repository;
_uow = uow;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Save(TModel model)
{
if (!ModelState.IsValid)
return Json(ModelState);
try
{
if (model.Id > 0)
{
var record = await _repository.GetAsync((int)model.Id);
if (record == null)
return Json(new NotFound());
_mapper.Map(model, record);
}
else
{
var entity = _mapper.Map<TEntity>(model);
_repository.Add(entity);
}
await _uow.CompleteAsync();
return Json(new Success("Record saved successfuly!"));
}
catch (Exception ex)
{
return Json(new InternalError(ex.Message));
}
}
[HttpPost]
public async Task<IActionResult> Delete(int id)
{
try
{
var record = await _repository.GetAsync(id);
if (record == null)
return Json(new NotFound());
record.IsDeleted = true;
await _uow.CompleteAsync();
return Json(new Success("Record successfully deleted."));
}
catch (Exception ex)
{
return Json(new InternalError(ex.Message));
}
}
(int)model.Id
why do you need to cast it? Why not make it an int in the model? \$\endgroup\$virtual
so they can be overridden if needed in subclassed controllers. \$\endgroup\$