Tôi đã xác định Lớp Người tài sản Ngày sinh là nullable DateTime?, vậy tại sao không phải toán tử kết hợp không hoạt động trong ví dụ sau?C# ?? null câu hỏi điều hành coalescing
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? DBNull.Value;
Lỗi trình biên dịch tôi nhận là "Toán tử '??' không thể áp dụng cho các toán hạng kiểu 'System.DateTime?' và 'System.DBNull"
Sau đây cũng có một lỗi biên dịch:
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
(person.Birthday == null) ? person.Birthday:DBNull.Value;
tôi đã thêm một dàn diễn viên đến (object) theo khuyến cáo của Refactor, và nó được biên dịch, nhưng không hoạt động đúng và giá trị được lưu trữ trong sqlserver db là null trong cả hai trường hợp.
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? (object)DBNull.Value;
Ai đó có thể giải thích những gì đang diễn ra ở đây?
tôi cần phải sử dụng mã vụng về như sau:
if (person.Birthday == null)
cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value
= DBNull.Value;
else cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value =
person.Birthday;
Bản sao của http://stackoverflow.com/questions/218808/c-ado-net-nulls-and-dbnull-is-there-more-efficient-syntax – sgriffinusa
Có được điều này từ bài đăng khác: SqlDbType.SmallDateTime)) .Value = person.Birthday ?? (đối tượng) DBNull.Value; Cảm ơn! –