Search code examples
c#asp.net-mvcasynchronousmodel-view-controllercontroller

Saving the changes with AddSync


i'm a beginner in c# and i am having a problem in the code, i am using the Edit method as a Index, so i'm using the AddAsync, but when i run the code it just skips the line, and also its not saving.

this is the edit method:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(int id, IEnumerable<ModelProfileTraceClass> model)
        {
            try
            {
                var selectedClasses = model.Where(m => m.IsSelected).ToList();
                var obj = Mapper.Map<IEnumerable<ProfileTraceClass>>(selectedClasses);

                foreach (var objs in obj)
                {
                    await _appServiceProfileTraceClass.AddAsync(objs).ConfigureAwait(false);

                }
                return RedirectToAction("Index", "DB2ProfileTraceType", new { id = ViewBag.ProfileTraceTypeId });
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
                return View(model);
            }
        }
 public async Task<ActionResult> Edit(int id)
 {
     // Usei ToList() para evitar o erro de execução 
     var profileTraceClassList = _appServiceProfileTraceClass.GetAll().ToList();
     var traceClassList = _appServiceTraceClass.GetAll().ToList();
 
     var traceClassData = (from traceClass in traceClassList
                           join profileTraceClass in profileTraceClassList
                           on traceClass.Id equals profileTraceClass.TraceClassId into traceClassesGroup
                           from profileTraceClass in traceClassesGroup.DefaultIfEmpty()
                           select new ModelProfileTraceClass
                           {
                               TraceClassId = traceClass.Id,
                               ProfileTraceId = id,
                               IsSelected = profileTraceClass != null && profileTraceClass.ProfileTraceId == id,
                               Description = traceClass.Description
 
                           }).ToList();
     ViewBag.ProfileTraceTypeId = id;
 
     return View(traceClassData);
 }

this is the AppService and IAppService

{
 public AppServiceProfileTraceClass(IServiceProfileTraceClass service) : base(service) { }
 
 //public async Task<int> SaveChangesAsync()
 //{
 //    return await _service.SaveChangesAsync();
 //}
} ```

 ``` public interface IAppServiceProfileTraceClass : IAppServiceBase<ProfileTraceClass>
 {
 } ```

Solution

  • Looks like you have used AddAsync method on DbContext.

    First of all, AddAsync and its synchoronous counterpart Add just begin tracking the entity, do not add it to database. As it is stated in the docs:

    Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

    From there, you can see you need to call SaveChanges method (or its async counterpart SaveChangesAsync).

    Moreover, in AddAsync docs we can read:

    This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.

    Conslusion

    You should use Add synchronous method for adding entities to databse context and use SaveChanges (or SaveChangesAsync) to actually persist data in database.