【发布时间】:2016-01-15 21:51:49
【问题描述】:
我正在使用 Visual Studio 2015 社区版和 MVC 5,实体框架 6。我刚刚学会了如何使用 async 和 await 进行异步调用。
现在在我的项目中,我只有 CRUD 操作,并且对于所有操作,我都编写了存储过程,除了调用存储过程之外,我的 API 中没有更多的业务逻辑。所以我使用 async 和 await 来调用存储过程。
但是这样做,我得到了错误,
'int' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
我的代码是,
[HttpPost]
public async Task<IHttpActionResult> AddContactEmails(Contacts data)
{
using (JodoDataEntities DB = new JodoDataEntities())
{
int Result = await DB.AddContacts(data.userId, data.data);
return Ok();
}
}
我的存储过程非常简单,我从中返回任何东西,仍然 EF 将其作为 int 返回类型。
ALTER PROCEDURE [dbo].[AddContacts]
@userId nvarchar(128),
@contacts nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
if not exists(select top 1 * from Contacts where userId = @userId)
begin
insert into Contacts (userId, contacts) VALUES (@userId, @contacts)
end
END
EF 代码(自动生成),
public virtual int AddContacts(string userId, string contacts)
{
var userIdParameter = userId != null ?
new ObjectParameter("userId", userId) :
new ObjectParameter("userId", typeof(string));
var contactsParameter = contacts != null ?
new ObjectParameter("contacts", contacts) :
new ObjectParameter("contacts", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("AddContacts", userIdParameter, contactsParameter);
}
1)。为什么我在调用方法时收到此错误?
2)。我需要在哪里进行更改才能使其正常工作?
3)。所以当我的 API 中只有 SP 调用时,我真的需要使用 async 和 await 吗?
【问题讨论】:
-
由于您的方法不可等待,如果您认为需要使用 async/await,则必须将它们包装在 Task.Run 之类的东西中。
标签: asp.net asp.net-mvc-5 async-await task-parallel-library entity-framework-6.1