SQL String or binary data would be truncated

时间:2017-04-10 02:45:13

标签: sql ef-code-first asp.net-mvc-viewmodel

I'm trying to search the max ID in the database, then increment it by 1 for each new entry as shown below:

var query2 = dbb.Database.SqlQuery<patient_visit>("SELECT MAX(CAST(SUBSTRING(pvid, 3, 10) AS int)) FROM patient_visit");

            if (query2 != null)
            {
                objDetails.pvid = query2.ToString();
                objDetails.pvid += 1;
                objDetails.pvid = "PV" + objDetails.pvid;
            }

string sql = "INSERT INTO patient_visit (pvid,paid) " +
                         "VALUES('" + objDetails.pvid + "', '" + paid + "')";

But when i try to insert it in the database, it gives out error

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: String or binary data would be truncated.

I've tried running the query in SQL Server and checked the value of 'pvid', it is 10 so after i include 'PV' to the integer pvid, it should be 12. So it should be fine, but why did i get that error? Please can anyone help me?

[Key]
    [MaxLength(20), MinLength(12)]
    public string pvid { get; set; }

When i replace the pvid with hard code ID, it works just fine. Why is this happening?

P/S: I know its not advisable to simply concatenate the input data with the query, but i've also tried querying using parameterized query but it gives same error.

string sql = "INSERT INTO patient_visit (pvid,paid) " +
                         "VALUES(@pvid, @paid)";
List<SqlParameter> parameterList = new List<SqlParameter>();
parameterList.Add(new SqlParameter("@pvid", objDetails.pvid));
parameterList.Add(new SqlParameter("@paid", paid));
SqlParameter[] parameters = parameterList.ToArray();
dbb.Database.ExecuteSqlCommand(sql, parameters);

1 个答案:

答案 0 :(得分:0)

检查您尝试将数据放入的列的字段长度。

在列为varchar(10)之前我遇到过这个问题,我试图连接两个每个包含6个字符的char字符串。使它们长12个字符。 2比目标字段长。

您的问题可能类似。