我仍然在学习如何在C#和WebApi中正确地使用依赖项,并出现了一个问题。我有一个注册用户的存储库,但是由于它是一个async task空方法,所以它不会返回任何内容。所以问题是,做这件事的最好方法是什么?它将使用Task<T>并在Controller中处理结果?
课程:
public interface IGeneral
{
Task RegisterAsync(UserModel model);
}
public class General : BaseRepository, IGeneral
{
public General(Context context) : base(context)
{
}
public async Task RegisterAsync(UserModel model)
{
var result = await Context.User.Where(a => a.Email == model.Email).FirstOrDefaultAsync();
if(result != null)
{
await Context.User.AddAsync(new Data.Access.Models.User
{ Date = DateTime.Now, Email = model.Email, Name = model.Name, Password = model.Password });
await Context.SaveChangesAsync();
}
}
}
public abstract class BaseRepository
{
protected readonly Context Context;
public BaseRepository(Context context)
{
Context = context;
}
}发布于 2020-09-23 06:44:23
你在问题中提出的可能解决办法
public async Task<bool> RegisterAsync(UserModel model)
{
bool operationResult = false;
var result = await Context.User.Where(a => a.Email == model.Email).FirstOrDefaultAsync();
if (result != null)
{
await Context.User.AddAsync(new Data.Access.Models.User
{ Date = DateTime.Now, Email = model.Email, Name = model.Name, Password = model.Password });
if(await Context.SaveChangesAsync() > 0)
{
operationResult = true;
}
}
return operationResult;
}从MSDN文档中我们知道SaveChangesAsync()签名public virtual System.Threading.Tasks.Task<int> SaveChangesAsync ();
返回一个int值。
如果检查大于零的结果,则断言已发生更改,并已使更改保持不变。
发布于 2020-09-23 06:10:38
不应该使用Task<T>返回类型的RegisterAsync(UserModel model)方法来处理控制器中的结果,因为
必须在methods.
可以保持此方法的原样,并且可以在服务中或控制器中适当地使用try catch块,这取决于您想要在异常时发送什么,方法是考虑客户端(用户)*的类型。
https://stackoverflow.com/questions/64021726
复制相似问题