Utilisation du Pattern "Repository"
Bonjour!
je me suis servi de ce très bon tutoriel http://www.asp.net/mvc/tutorials/get...vc-application pour utiliser le pattern Repository dans mon application. Mais il se trouve que je ne parviens pas à bien l'exploiter.
Je suis en train de réaliser une mini application de gestion de stock pour le suivi des stocks de matériel d'un entrepot.
Voici une parti de la BD:
Matériels (MaterielID, Designation, QuantiteEnStock)
Entrees (EntreeID, MaterielID, QuantiteEntree, DateEntree)
Comme je le disais plus haut, voici le pattern repository que j'ai utilisé:
- la classe GenericRepository.cs
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| namespace MvcCodeFirst.Models
{
public class GenericRepository<TEntity> where TEntity : class
{
internal CodeFirstContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(CodeFirstContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
} |
- la classe UnitOfWork.cs
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| namespace MvcCodeFirst.Models
{
public class UnitOfWork : IDisposable
{
private CodeFirstContext context = new CodeFirstContext();
private GenericRepository<Entree> entreeRepository;
private GenericRepository<Materiel> materielRepository;
public GenericRepository<Entree> EntreeRepository
{
get
{
if (this.entreeRepository == null)
{
this.entreeRepository = new GenericRepository<Entree>(context);
}
return entreeRepository;
}
}
public GenericRepository<Materiel> MaterielRepository
{
get
{
if (this.materielRepository == null)
{
this.materielRepository = new GenericRepository<Materiel>(context);
}
return materielRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
} |
Voici également les controleurs que j'ai utilisés:
-EntreeController.cs
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
| namespace MvcCodeFirst.Controllers
{
public class EntreeController : Controller
{
private UnitOfWork unitOfWork = new UnitOfWork();
private CodeFirstContext db = new CodeFirstContext();
//
// GET: /Entree/
public ViewResult Index()
{
var entrees = unitOfWork.EntreeRepository.Get(includeProperties : "Materiel");
return View(entrees.ToList());
}
//
// GET: /Entree/Details/5
public ViewResult Details(int id)
{
Entree entree = unitOfWork.EntreeRepository.GetByID(id);
return View(entree);
}
//
// GET: /Entree/Create
public ActionResult Create()
{
PopulateMaterielsDropDownList();
return View();
}
//
// POST: /Entree/Create
[HttpPost]
public ActionResult Create(Entree entree)
{
try
{
if (ModelState.IsValid)
{
entree.DateEntree = DateTime.Now;
unitOfWork.EntreeRepository.Insert(entree);
unitOfWork.Save();
Materiel matos = new Materiel();
var dernier = from l in db.Entrees
orderby entree.EntreeID
select l.MaterielID;
matos.MaterielID = dernier.Last();
return RedirectToAction("Index");
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
PopulateMaterielsDropDownList(entree.MaterielID);
return View(entree);
}
//
// GET: /Entree/Edit/5
public ActionResult Edit(int id)
{
Entree entree = unitOfWork.EntreeRepository.GetByID(id);
PopulateMaterielsDropDownList(entree.MaterielID);
return View(entree);
}
//
// POST: /Entree/Edit/5
[HttpPost]
public ActionResult Edit(Entree entree)
{
try
{
if (ModelState.IsValid)
{
unitOfWork.EntreeRepository.Update(entree);
unitOfWork.Save();
return RedirectToAction("Index");
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
PopulateMaterielsDropDownList(entree.MaterielID);
return View(entree);
}
private void PopulateMaterielsDropDownList(object selectedMateriel = null)
{
var materielsQuery = unitOfWork.MaterielRepository.Get(
orderBy: q => q.OrderBy(d => d.Designation));
ViewBag.MaterielID = new SelectList(materielsQuery, "MaterielID", "Designation", selectedMateriel);
}
//
// GET: /Entree/Delete/5
public ActionResult Delete(int id)
{
Entree entree = unitOfWork.EntreeRepository.GetByID(id);
return View(entree);
}
//
// POST: /Entree/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Entree entree = unitOfWork.EntreeRepository.GetByID(id);
unitOfWork.EntreeRepository.Delete(id);
unitOfWork.Save();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
unitOfWork.Dispose();
base.Dispose(disposing);
}
}
} |
et MaterielController.cs
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| namespace MvcCodeFirst.Controllers
{
public class MaterielController : Controller
{
private CodeFirstContext db = new CodeFirstContext();
//
// GET: /Materiel/
public ViewResult Index()
{
return View(db.Materiels.ToList());
}
//
// GET: /Materiel/Details/5
public ViewResult Details(int id)
{
Materiel materiel = db.Materiels.Find(id);
return View(materiel);
}
//
// GET: /Materiel/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Materiel/Create
[HttpPost]
public ActionResult Create(Materiel materiel)
{
if (ModelState.IsValid)
{
db.Materiels.Add(materiel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(materiel);
}
//
// GET: /Materiel/Edit/5
public ActionResult Edit(int id)
{
Materiel materiel = db.Materiels.Find(id);
return View(materiel);
}
//
// POST: /Materiel/Edit/5
[HttpPost]
public ActionResult Edit(Materiel materiel)
{
if (ModelState.IsValid)
{
db.Entry(materiel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(materiel);
}
//
// GET: /Materiel/Delete/5
public ActionResult Delete(int id)
{
Materiel materiel = db.Materiels.Find(id);
return View(materiel);
}
//
// POST: /Materiel/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Materiel materiel = db.Materiels.Find(id);
db.Materiels.Remove(materiel);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
} |
Ce que je souhaite faire est de mettre à jour le stock de matériel à chaque nouvelle entrée de matériel; je m'explique:
j’ai l’entrée suivante : Entrees (1, vélo, 12, 12/12/2010) que j’enregistre via mon formulaire dans ma BD. Je veux que lors de l’enregistrement de cette entrée, que je puisse récupérer par exemple l’id du matériel (ici vélo) ainsi que la quantité de matériel entrée correspondante (ici 12 vélo), et de faire une mise à jour de ce matériel dans la table Matériels à savoir la quantiteEnStock du matériel : Matériels(1, Vélo, 12)
Une deuxième entrée donnera ceci : Entrees (2,Vélo, 13, 12/12/2010) et la mise à jour ceci Matériels(1, Vélo, 25). Comme vous le voyez, la quantiteEnStock est passée de 12 à 25. C’est cette mise à jour que je souhaite réaliser.
J’espère que j’ai pu bien vous éclairer sur mon problème !
merci d'avance!