2
I am trying to insert training record into a list that is being used in place of a database, but somewhere in the application it gets lost and the list keeps only the record that was entered via code in the Trainingrepository class constructor. At first I thought it was because of the controller that is always being called and so would be cleared my list.
Repository
public class TrainingRepository : ITrainingRepository
{
private List<Treinamento> allTrainings;
private List<Treinamento> trainingData = new List<Treinamento>(); // Repositório
public TrainingRepository()
{
allTrainings = new List<Treinamento>();
trainingData.Add(new Treinamento() { ID = 1, Name = "João da Silva", Duration = "45min", StartDate = DateTime.Parse("10/10/2015"), EndDate = DateTime.Parse("31/10/2015"), Instructor = "Paula", Time = "4:00PM" });
allTrainings.AddRange(trainingData.ToList<Treinamento>());
}
public IEnumerable<Treinamento> GetTrainings()
{
return allTrainings;
}
public Treinamento GetTrainingByID(int id)
{
return allTrainings.Find(t => t.ID == id);
}
public void InsertTraining(Treinamento training)
{
training.ID = (from b in trainingData orderby b.ID descending select b.ID).FirstOrDefault() + 1;
trainingData.Add(new Treinamento()
{
ID = training.ID,
Name = training.Name,
Instructor = training.Instructor,
StartDate = training.StartDate,
EndDate = training.EndDate,
Time = training.Time,
Duration = training.Duration
});
}
public List<string> GetInstructor()
{
var mainItems = (from key in trainingData select key.Instructor).Distinct().ToList();
return mainItems.ToList();
}
}
Controller
public class HomeController : Controller
{
TrainingRepository _trainingRepository = new TrainingRepository();
public ActionResult Index()
{
List<Treinamento> allTrainings = _trainingRepository.GetTrainings().ToList();
return View(allTrainings);
}
[HttpGet]
public ActionResult CreatePartialView()
{
return PartialView("CreatePartialView");
}
[HttpPost]
public void Create(Treinamento training)
{
_trainingRepository.InsertTraining(training);
}
[HttpGet]
public JsonResult GetInstructorList()
{
var allInstructors = _trainingRepository.GetInstructor().ToList();
return Json(allInstructors, JsonRequestBehavior.AllowGet);
}
}
Toby, it worked. Thank you! I just didn’t understand the term you quoted from Unitofwork. What it means?
– Kelly Soares
I don’t know how to explain it, but basically it would be an object that will coordinate a transaction involving multiple repositories.
– Tobias Mesquita
Thanks for your help Toby!
– Kelly Soares