Perché non riesco a inserire dbnull.value in un campo di immagine nullabile in SQL Server 2005?
-
13-11-2019 - |
Domanda
Perché non riesco a inserire DBNull.Value
in un campo NULLABILE image
in SQL Server 2005?
Ho provato questo codice:
SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=PrescriptionTrackingSystem;Integrated Security=True");
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
SqlCommand command = new SqlCommand(@"INSERT INTO Customer(
ID
,Name
,TelephoneNumber
,DateOfBirth,
InsuranceProvider,
PolicyNumber,Photo)
VALUES(
@ID
,@Name
,@TelephoneNumber
,@DateOfBirth,
@InsuranceProvider,
@PolicyNumber,
@Photo)", conn);
command.Transaction = transaction;
command.Parameters.AddWithValue("@ID", 1000);
command.Parameters.AddWithValue("@Name", item.Name);
command.Parameters.AddWithValue("@TelephoneNumber", item.TelephoneNumber);
if (item.DateOfBirth != null)
{
command.Parameters.AddWithValue("@DateOfBirth", item.DateOfBirth);
}
else
{
command.Parameters.AddWithValue("@DateOfBirth", DBNull.Value);
}
command.Parameters.AddWithValue("@InsuranceProvider", item.InsuranceProvider);
command.Parameters.AddWithValue("@PolicyNumber", item.PolicyNumber);
if (item.Photo != null)
{
command.Parameters.AddWithValue("@Photo", item.Photo);
}
else
{
command.Parameters.AddWithValue("@Photo", DBNull.Value);
}
int count = command.ExecuteNonQuery();
transaction.Commit();
conn.Close();
.
Item è di tipo Customer
.
public class Customer
{
public string Name { get; set; }
public DateTime? DateOfBirth { get; set; }
public string TelephoneNumber { get; set; }
public string InsuranceProvider { get; set; }
public int? PolicyNumber { get; set; }
public byte [] Photo { get; set; }
}
.
Quando si inserisce ottengo questa eccezione:
Operand type clash: nvarchar is incompatible with image
.
Perché DBNull.Value
ha problemi solo con image
?Perché non con datetime
?
Soluzione
Potresti provare questo:
command.Parameters.Add("@Photo", SqlDbType.Image).Value = DBNull.Value;
. Altri suggerimenti
Penso che questo potrebbe essere a che fare con il fatto che non si definisce esplicitamente il SQLParameter.SQLDBTYPE e pensare che assumenterà Nvarchar.Invece di utilizzare addwithValue, provare ad aggiungere un nuovo SQLParameter e impostare SQLDBTYPE esplicitamente su SQLDBTYPE.Image.
Ecco il msdn ref Quali stati predefiniti è nvarchar.
È necessario specificare esplicitamente il tipo di parametro come SQLDBTYPE.Image
Ho risolto questo simile:
If (Photo.Equals(DBNull.Value)) Then
cmd.Parameters.Add("Photo", SqlDbType.Image).Value = DBNull.Value
Else
cmd.Parameters.AddWithValue("Photo", Photo)
End If
.