Insert data with LIST in ASP.NET MVC

2

I'm trying to insert training log into a list that is being used instead 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 constructor of the TrainingRepository class . At first I thought it was because of the controller that is always being called and so my list would be cleaned.

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);
    }
}
    
asked by anonymous 16.09.2015 / 18:45

1 answer

3

Since you make a request to the Controller, a new instance of it is instantiated and you are creating a new repository together.

As it is interesting to keep a UnitOfWork for each instance of the Controller, it is really interesting that the repository is instantiating each request.

On the other hand, its Banco de Dados (a.k.a. List allTrainings') must survive persist after each request, in this case the list must be instance statically.

In this case, you will need to lock the List whenever you need to change it, ie during insertion or removal, to prevent simultaneous accesses from causing inconsistencies.

I would also like to point out two more points:

  • I do not see the need to mater these two training lists.
  • You should not use .List() too much, each 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);
        }
    }
    
        
    16.09.2015 / 19:16