Base solution for your next web application
Open Closed

When Register a user, why do I need to call SaveChangesAsync #381


User avatar
0
spencerdoe created

Hi,

I have created a sample Asp.NET project to see how basic identity works? I found out after calling createAsync(), the user data will be stored in database like below:

if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
              <span style="color:#FF4000">  var result = await UserManager.CreateAsync(user, model.Password);</span>
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

But in module zero , I found that after calling createAsync, there is a SaveChangesAsync function. Why do I need to call this? And when does the data actually write to the DB? It seems that after the CreateAsync function, the data is not stored in DB right away.

Your help is quite appreciated!


1 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    As you know, EntityFramework does not save new inserted entities to database unless you call SaveChanges method. This is why you should call it to make it's inserted. This is needed to get User's Id from database. Otherwise it remains 0 after CreateAsync method. If you don't call SaveChanges, it's called by ABP after your method finishes. But it you need user's Id in some place of the method, you call SaveChanges. For more info about UOW, see it's document: <a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work">http://www.aspnetboilerplate.com/Pages/ ... it-Of-Work</a>