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

asp.net-core asp.net-identity async-await asynchronous entity-framework-core

Question

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.

1
2
12/29/2018 8:25:55 PM

Accepted Answer

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;
4
12/29/2018 8:53:38 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow