SQL Server 2005DBNull.Value
のnull許容フィールドに挿入できないのはなぜですか?image
私はこのコードを試しました:
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();
アイテムはタイプ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; }
}
挿入すると、次の例外が発生します。
Operand type clash: nvarchar is incompatible with image
なぜDBNull.Value
問題があるのimage
ですか?どうしてdatetime
?