User711641945 posted
Hi karol,
I think you could try to use Generic Repository to avoid code repetion.
Here is a sample:
public class BaseController<T>:Controller where T:class
{
private readonly MyDbContext _context;
public BaseController(MyDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await _context.Set<T>().ToListAsync());
}
// GET: Tests/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var test = await _context.Set<T>()
.FindAsync(id);
if (test == null)
{
return NotFound();
}
return View(test);
}
// GET: Tests/Create
public IActionResult Create()
{
return View();
}
// POST: Tests/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult<T>> Create(T test)
{
if (ModelState.IsValid)
{
_context.Add(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(test);
}
//.....
}
And you just need create a controller which inherits the BaseController and pass the model you want.No need to write the same code for several times:
public class TestsController : BaseController<Test>
{
private readonly MyDbContext _context;
public TestsController(MyDbContext context):base(context)
{
_context = context;
}
}
Best Regards,
Rena