我有一个如下所示的存储过程:
ALTER PROCEDURE [dbo].[sp_SearchUnit]
@UnitName VARCHAR(50)
AS
BEGIN
SELECT
b.NewBuildingId,
b.NewBuildingName,
u.PropertyUnitId,
u.[Owner],
p.FirstName,
p.MiddleName,
p.LastName,
u.ParkingAreaSqMeters,
u.PostingDateTime,
u.TypeOfUnit,
u.UnitName,
u.WithParking
FROM
[Property].[Unit_Rev] AS u
LEFT JOIN
[dbo].[Building_Rev] AS b ON u.BuildingId = b.NewBuildingId
LEFT JOIN
[dbo].[Person] AS p ON u.Owner = p.PersonId
WHERE
u.UnitName LIKE '%'+@UnitName+'%'
END
在我的Web API中,我像这样访问此存储过程:
[HttpPost]
[Route("api/searchunitbyunitname")]
public async Task<List<SearchUnit>> SearchUnitByUnitName()
{
var req = HttpContext.Current.Request;
var unitName = req["unitname"];
const string query = "sp_SearchUnit @UnitName";
using (var db = new PmisDbContext())
{
try
{
object[] parameters =
{
new SqlParameter
{
ParameterName = "@UnitName",
Value = unitName,
Direction = ParameterDirection.Input
}
};
var list = await db.Database.SqlQuery<SearchUnit>(query, parameters).ToListAsync();
return list;
}
catch(Exception ex)
{
return null;
}
}
}
“ SearchUnit”的类是:
public class SearchUnit
{
public string NewBuildingId { get; set; }
public string NewBuildingName { get; set; }
public string PropertyUnitId { get; set; }
public string Owner { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string ParkingAreaSqMeters { get; set; }
public string PostingDateTime { get; set; }
public string TypeOfUnit { get; set; }
public string UnitName { get; set; }
public string WithParking { get; set; }
}
为什么会出现此错误:
从实例化的“ System.Int32”类型到“ System.String”类型的指定强制转换无效
如果我在SQL Server Management Studio中运行存储过程,则会得到结果。
谢谢您的帮助。
答案 0 :(得分:1)
必须确保用声明的SqlQuery
中使用的所有目标类属性与从数据库中检索到的物化数据类型(例如,列名后缀为“ Id”的数据类型应调整为int
:
public int NewBuildingId { get; set; }
public int PropertyUnitId { get; set; }
在目标类中为所有属性使用string
数据类型不是一个好主意,因为在使用Database.SqlQuery<TElement>
方法时,不会自动将物化数值数据类型转换为string
类型。