[英]Trying to execute Insert and Update SQL stored procedures in Dapper, getting a conversion type error [closed]
我正在尝试使用 Dapper 在 .NET 中构建我的 Web API。 虽然选择已成功,但插入和更新尚未成功。 基本上,它向我发送了一个错误,它无法将一种字符串类型转换为 integer,我不确定它为什么会给我这个错误。
SQL 插入存储过程:
ALTER proc [dbo].[MotionPictures_Insert]
@Name nvarchar(50)
, @Description nvarchar(500)
, @ReleaseYear int
, @Id int OUTPUT
as
BEGIN
INSERT INTO [dbo].[MotionPictures]
([Name]
,[Description]
,[ReleaseYear])
VALUES
(@Name
,@Description
,@ReleaseYear)
SET @Id = SCOPE_IDENTITY()
END
电影资料库片段
public async Task<MotionPicture> CreateMotionPicture(MotionPictureAddRequest movie)
{
var procedureName = "MotionPictures_Insert";
var parameters = new DynamicParameters();
parameters.Add("Name", movie.Name, DbType.String);
parameters.Add("Description", movie.Description, DbType.String);
parameters.Add("Release Year", movie.ReleaseYear, DbType.Int32);
using (var connection = _context.CreateConnection())
{
var id = await connection.QuerySingleAsync<int>(procedureName, parameters, commandType: CommandType.StoredProcedure);
var createdMovie = new MotionPicture
{
Id = id,
Name = movie.Name,
Description = movie.Description,
ReleaseYear = movie.ReleaseYear
};
return createdMovie;
}
}
Model 和请求片段
public class MotionPicture
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int ReleaseYear { get; set; }
}
public class MotionPictureAddRequest
{
[Required]
[StringLength(50, ErrorMessage = "Name cannot be longer than 50 characters.")]
public string Name { get; set; }
[StringLength(500, ErrorMessage = "Description cannot be longer than 500 characters.")]
public string? Description { get; set; }
[Required]
[StringLength(4, MinimumLength = 4, ErrorMessage = "Release year must be 4 digits only.")]
public int ReleaseYear { get; set; }
}
Controller 片段
[HttpPost]
public async Task<IActionResult> CreateMotionPicture(MotionPictureAddRequest movie)
{
try
{
var createdMovie = await _movieService.CreateMotionPicture(movie);
return CreatedAtRoute("MotionPictureById", new { id = createdMovie.Id }, createdMovie);
}
catch (Exception ex)
{
//log error
return StatusCode(500, ex.Message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.