Search code examples
asynchronousasp.net-coreasync-awaitasp.net-identityentity-framework-core

How to check if Entity item was added in Async C# MVC Core method


I am writing my own implementation of IUserStore and IUserPasswordStore and I need to prepare async method CreateAsync which will return IdentityResult. So far I have this:

    public async Task<IdentityResult> CreateAsync(User user)
    {
        Users.Add(user);
        //await Users.AddAsync(user);
        SaveChanges();
        //await SaveChangesAsync(user);
        //alternative version is commented

        if (<What to put there>)
        {
            return IdentityResult.Success;
        }
        return IdentityResult.Failed(new IdentityError { Description = $"Could not insert user {user.Email}." });
    }

I am really not sure what should I put inside if. I can only use async methods, so there is no really any result when I run this function. Any tips? I'd really appreciate.

Usually I'd just use Any() but this implementation doesn't allow me. If you need more code, just ask in comment, I'll provide, however I think this is enough info for question.


Solution

  • SaveChanges() and await SaveChangesAsync(); return an int that is the number of affected records if the save operation has done successfully. You can check the returned value and return the relevant result.

    var success = await context.SaveChangesAsync() > 0;
    
    return success
        ? IdentityResult.Success
        : IdentityResult.Failed;