尝试存储guid时转换错误(字符串到uniqueidentifier)

时间:2017-10-03 13:26:45

标签: c# sql .net

我提供的代码请帮助我,

当我尝试获取xml数据并在SQL存储时,我收到错误"转换失败"

foreach (entity ent in _entity) 
{               
    con.Open();
    string query = "INSERT INTO tblDemo (ContractType,P2P_Request_SYSID,EntityName,SYSID,ETag,Name,EntityInstanceId,EntityVersion) Values ('" + ent.Type+"','" +ent.P2P_Request_SYSID + "','" + ent.EntityName + "','" + ent.SYSID + "','" + ent.ETag + "','" + ent.Name + "','" + ent.EntityInstanceId + "','" + ent.EntityVersion + "')";
    SqlCommand cmd = new SqlCommand(query, con);

    cmd.ExecuteNonQuery();
    con.Close();
}

1 个答案:

答案 0 :(得分:1)

用户参数并尝试指定uniqueidentier

的数据类型
foreach (entity ent in _entity) 
{               
    con.Open();
    string query = @"INSERT INTO tblDemo (ContractType,P2P_Request_SYSID,EntityName,SYSID,
                     ETag,Name,EntityInstanceId,EntityVersion)
                     Values (@Type,@P2P_Request_SYSID,@EntityName,@SYSID,@ETag,@Name,
                     @EntityInstanceId,@EntityVersion)";
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@Type", ent.Type);
    cmd.Parameters.Add( "@P2P_Request_SYSID", SqlDbType.UniqueIdentifier, 16 ).Value = ent.P2P_Request_SYSID;
    cmd.Parameters.AddWithValue("@EntityName", ent.EntityName);
    cmd.Parameters.Add( "@SYSID", SqlDbType.UniqueIdentifier, 16 ).Value = ent.SYSID;
    cmd.Parameters.AddWithValue("@ETag", ent.ETag);
    cmd.Parameters.AddWithValue("@Name", ent.Name);
    cmd.Parameters.Add( "@EntityInstanceId", SqlDbType.UniqueIdentifier, 16 ).Value = ent.EntityInstanceId;
    cmd.Parameters.AddWithValue("@EntityVersion", ent.EntityVersion);

    cmd.ExecuteNonQuery();
    con.Close();
}