Insert data with LIST into ASP.NET MVC

Asked

Viewed 372 times

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);
    }
}

1 answer

3


When you make a request to the Controller, a new instance of the Controller is instantiated and with this you are creating a new repository together.

Since it’s interesting to keep a Unitofwork for each instance of the Controller, it’s really interesting that the repository is instantiated with each request.

on the other hand, its Banco de Dados (a.k.a. List allTrainings`) must survive persisting after each request, in which case the list must be instantaneous in a static way.

In this case, you will need to lock the List whenever you need to change it, that is, during an insertion or removal, to avoid simultaneous accesses causing inconsistencies.

I would also like to make two further points:

  1. I see no need to keep these two training lists.
  2. You should not use the .List() too much, every time you use this feature, you are creating a new list, which in turn is occupying memory unnecessarily.

finally, if you need to pre-load your list, then create a static method to create the list.

Repository

public class TrainingRepository : ITrainingRepository
{
    private static List<Treinamento> allTrainings = initTrainings();

    private static List<Treinamento> initTrainings()
    {
        var training = 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" 
        };
        var listOfTrainings = new List<Treinamento>();
        listOfTrainings.Add(training);
        return listOfTrainings;
    }

    public TrainingRepository()
    {

    }

    public IEnumerable<Treinamento> GetTrainings()
    {
        return TrainingRepository.allTrainings;
    }

    public Treinamento GetTrainingByID(int id)
    {
        return TrainingRepository.allTrainings.Find(t => t.ID == id);
    }

    public void InsertTraining(Treinamento training)
    {
        lock(TrainingRepository.allTrainings)
        {
            training.ID = (
                from b in TrainingRepository.allTrainings 
                orderby b.ID descending 
                select b.ID
            ).DefaultIfEmpty(0).First() + 1;        
            TrainingRepository.allTrainings.Add(training);
        }
    }

    public IEnumerable<string> GetInstructor()
    {
        return (from key in trainingData select key.Instructor).Distinct();
    }
}

Controller

public class HomeController : Controller
{

    TrainingRepository _trainingRepository = new TrainingRepository();

    public ActionResult Index()
    {
        List<Treinamento> allTrainings = _trainingRepository.GetTrainings();
        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();
        return Json(allInstructors, JsonRequestBehavior.AllowGet);
    }
}
  • Toby, it worked. Thank you! I just didn’t understand the term you quoted from Unitofwork. What it means?

  • 1

    I don’t know how to explain it, but basically it would be an object that will coordinate a transaction involving multiple repositories.

  • Thanks for your help Toby!

Browser other questions tagged

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