首页 > 解决方案 > 如何检查是否在 Async C# MVC Core 方法中添加了实体项

问题描述

我正在编写自己的 IUserStore 和 IUserPasswordStore 实现,我需要准备CreateAsync将返回的异步方法IdentityResult。到目前为止,我有这个:

    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}." });
    }

我真的不知道我应该在里面放什么if。我只能使用异步方法,所以当我运行这个函数时没有任何结果。有小费吗?我真的很感激。

通常我只是使用Any(),但这个实现不允许我。如果您需要更多代码,请在评论中提问,我会提供,但我认为这是足够的信息。

标签: asynchronousasp.net-coreasync-awaitasp.net-identityentity-framework-core

解决方案


SaveChanges()await SaveChangesAsync();如果保存操作成功完成,则返回一个 int 表示受影响记录的数量。您可以检查返回值并返回相关结果。

var success = await context.SaveChangesAsync() > 0;

return success
    ? IdentityResult.Success
    : IdentityResult.Failed;

推荐阅读