0
我想爲我的應用程序使用asp.net核心webapi實現異步CRUD功能。我被告知只使用存儲過程來處理對數據庫的任何請求。我已經實現了獲取請求的異步,但爲創建請求掙扎。有人能告訴我我的代碼中我做錯了什麼?int不包含Getawaiter + asp.net核心web api異步定義
我在代碼中的await行收到以下錯誤消息在我的倉庫方法
控制器的方法:
[HttpPost]
[Route("api/Movies")]
public async Task<IActionResult> CreateMovie([FromBody] MoviesDto movies)
{
if (movies == null)
{
return BadRequest();
}
// Check if movie exists
var movie = _moviesRepository.GetMovie(movies.MovieId);
if (movie == null)
{
return NotFound();
}
var results = Mapper.Map<Movies>(movies);
if (ModelState.IsValid)
{
await _moviesRepository.AddMovie(results);
}
return Ok(results);
}
庫方法:
public async Task AddMovie(Movies movie)
{
await _mrdbContext.Database.ExecuteSqlCommand("dbo.spInsertMovie {0}, {1}, {2}, {3}, {4}, {5}", movie.Title,movie.ReleaseYear,movie.Plot,movie.MovieLength,"Ranjit Menon","");
}
新的存儲庫方法:
public async Task AddMovie(Movies movie)
{
object[] parameters =
{
new SqlParameter("@val1", movie.Title),
new SqlParameter("@val2", movie.ReleaseYear),
new SqlParameter("@val3", movie.Plot),
new SqlParameter("@val4", movie.MovieLength),
new SqlParameter("@val5", "Ranjit Menon"),
new SqlParameter
{
ParameterName = "@retVal",
SqlDbType = SqlDbType.Int,
Direction = ParameterDirection.Output,
Value = -1
}
};
await _mrdbContext.Database.ExecuteSqlCommandAsync("EXEC @retVal = dbo.spInsertMovie @val1, @val2, @val3, @val4,@val5", CancellationToken.None , parameters);
}
存儲過程:
CREATE PROCEDURE [dbo].[spInsertMovie]
(@Title varchar(50),
@ReleaseYear int,
@Plot varchar(50),
@MovieLength int,
@CreatedBy varchar(20)
)
AS
BEGIN
set nocount on
----------------------------------------
-- variables
----------------------------------------
-- error
declare @ErrorMessage nvarchar(2048), @ErrorSeverity int, @ErrorState int, @MovieID int
----------------------------------------
-- insert record
----------------------------------------
begin try
-- insert record
insert into [dbo].[Movies]
([Title]
,[ReleaseYear]
,[Plot]
,[MovieLength]
,[CreatedBy]
,[UpdatedBy])
values
(@Title
,@ReleaseYear
,@Plot
,@MovieLength
,@CreatedBy
,@CreatedBy)
-- get assigned id
set @MovieID = scope_identity()
end try
begin catch
select @ErrorMessage = dbo.fnGetErrorMessage('Insert Movie Record', error_message(), object_schema_name(@@procid), object_name(@@procid), error_line()), @ErrorSeverity = error_severity(), @ErrorState = error_state();
raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);
return
end catch
-- return assigned id
select @MovieID as MovieID
END
我剛剛根據您的建議添加了新的存儲庫方法。但是我沒有看到該過程被調用。我打開了我的分析器來捕獲通話。我已通過傳遞相同的參數值在後端測試了存儲過程,並通過返回新生成的Movie ID正常工作。我還更新了帖子以包含商店程序 – Tom
@Tom是否會拋出異常或以任何方式失敗? – Andrew
嗨安德魯,我看到沒有例外拋出,這使我很難理解爲什麼它不工作。 – Tom