【问题标题】:The specified cast from a materialized 'System.Int32' type to the 'System.String' type is not valid when using stored procedure使用存储过程时,从具体化的“System.Int32”类型到“System.String”类型的指定转换无效
【发布时间】:2018-08-02 03:09:06
【问题描述】:

我有一个如下所示的存储过程:

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 中运行存储过程,我会得到我的结果。

感谢您的帮助。

【问题讨论】:

标签: c# sql-server asp.net-web-api stored-procedures


【解决方案1】:

有必要确保SqlQuery 中使用的所有目标类属性使用完全相同的数据类型与从数据库检索的具体化数据类型声明,例如后缀为“Id”的列名中的数据类型应调整为int

public int NewBuildingId { get; set; }

public int PropertyUnitId { get; set; }

对目标类中的所有属性使用string 数据类型并不是一个好主意,因为在使用Database.SqlQuery&lt;TElement&gt; 方法时,不会从具体化数值数据类型自动转换为string 类型。

【讨论】:

  • 感谢您提供的信息。它提高了我的知识。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
相关资源
最近更新 更多