异步/等待问题 [英] Async/Await problem
问题描述
我在代码中使用async时遇到了问题。我有一个从数据库中提取数据的异步查询。
I do have a problem with regards to using async in my code. I have an async query that pulls data from the database.
我的代码看起来像这样
//do a query to check if the data exist
var result = await MyAsyncCallToDatabase();
var result=await MyAsyncCallToDatabase();
if(result == null)
{
//将数据插入数据库
if(result==null) { //insert the data to the database
}
我是否需要等待异步调用才能完成获取所需的所有数据,然后再进行检查是否确实返回了一些内容,因为我现在遇到的是它返回null然后当我尝试执行if
条件内的插入时,SQL服务器返回一个异常,表示我无法插入重复数据。
Do I need to wait for my async call to finish getting all the data I want before doing the checking if it does return something because what I am experiencing right now is it returns null and then when I am trying to do the insert which is inside the if condition, SQL server returned an exception which says that I can't insert the duplicate data.
更新:提供更多信息
public class CustomerCreate
{
private readonly ICustomerRepository _customerPo;
public CustomerCreate(ICustomerRepository customerPo)
{
_customerPo = customerPo;
}
public async Task<int> CreateCustomer(PoCustomer custShipping)
{
var getCustomerShipping = await _customerPo.GetCustomerByKeyAsync(custShipping.CustomerId);
if (getCustomerShipping == null)
{
return await _customerPo.InsertAsync(custShipping);
}
return -1;
}
}
public interface ICustomerRepository
{
Task<int> InsertAsync(PoCustomer customer);
Task<PoCustomer> GetCustomerByKeyAsync(Guid key);
}
public class CustomerReposity : ICustomerRepository
{
public Task<int> InsertAsync(PoCustomer customer)
{
string sql = @"Insert into Customer
(FName, LName, BusinessName, Phone, Address1, Address2, City, State, Zip, Email,CustomerId )
Values
(@FName, @LName, @BusinessName, @Phone, @Address1, @Address2, @City, @State, @Zip, @Email,@CustomerId)";
using (var con = new SqlConnection(ConnectionString))
{
return (await con.ExecuteAsync(sql, customer));
}
}
public async Task<PoCustomer> GetCustomerByKeyAsync(Guid key)
{
string sql = "Select * from Customer Where CustomerId=@CustomerId";
using (var con = new SqlConnection(ConnectionString))
{
return (await con.QueryAsync<PoCustomer>(sql, new { CustomerId = key })).SingleOrDefault();
}
}
}
收到错误:
Error Received:
问候
推荐答案
MyAsyncCallToDatabase()的签名是什么?
What's the signature of MyAsyncCallToDatabase()?
这篇关于异步/等待问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!