Generic class for CRUD

Asked

Viewed 356 times

1

I have some common CRUD features in the database, such as cadastrar, buscar um registro, buscar todos os registros and excluir. For this, I am currently implementing a manager class each database table to perform the operations described.

I would like to know how to implement a single class to carry out these operations in common.

  • You intend to do the operations "in hand" or using some ORM?

  • Currently I do everything by Entity framework @jbueno

  • Okay, but then you don’t need any of that. Look, to save something in the database using EF, you just need to do contexto.Entidade.Add(objeto); contexto.SaveChanges()...

  • Is there any way to explain better what you intend to do? Use some pseudocode and such

1 answer

4

Zack, since you use MVC, I advise you to use one Controller generic.

That it could be something like

public abstract class Controller<TEntidade> : System.Web.Mvc.Controller
    where TEntidade: class
{
    private Exercicio10Cep.Models.ApplicationDbContext db = new Exercicio10Cep.Models.ApplicationDbContext();

    // GET: Paises
    public async Task<ActionResult> Index()
    {
        return View(await db.Set<TEntidade>().AsQueryable().ToListAsync());
    }

    // GET: Paises/Details/5
    public async Task<ActionResult> Details(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        TEntidade entidade = await db.Set<TEntidade>().FindAsync(id);
        if (entidade == null)
        {
            return HttpNotFound();
        }
        return View(entidade);
    }

    // GET: Paises/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Paises/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(TEntidade entidade)
    {
        if (ModelState.IsValid)
        {

            db.Set<TEntidade>().Add(entidade);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(entidade);
    }

    // GET: Paises/Edit/5
    public async Task<ActionResult> Edit(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var entidade = await db.Set<TEntidade>().FindAsync(id);
        if (entidade == null)
        {
            return HttpNotFound();
        }
        return View(entidade);
    }

    // POST: Paises/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit(TEntidade entidade)
    {
        if (ModelState.IsValid)
        {
            db.Entry<TEntidade>(entidade).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(entidade);
    }

    // GET: Paises/Delete/5
    public async Task<ActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var entidade = await db.Paises.FindAsync(id);
        if (entidade == null)
        {
            return HttpNotFound();
        }
        return View(entidade);
    }

    // POST: Paises/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(Guid id)
    {
        var entidade = await db.Set<TEntidade>().FindAsync(id);
        db.Set<TEntidade>().Remove(entidade);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

To use just do:

public class PaisesController : Controller<Pais>
{

}

public class EstadosController : Controller<Estado>
{

}

Thus it is not necessary to write any other code of the type Repositorio, Manager or DDD, because MVC is already a project standard, it does not make sense to write another project standard on top of a project standard, this would be to reinvent the wheel.

  • Good solution and no bale +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.