How to use null-coalescing operator with NULL date

My view model has a date property with a null value, such as ...

[DataType(DataType.Date)]
public DateTime? SanctionExpires { get; set; }

But when I try to use a zero coalescing operator like ...

var test = model.SanctionExpires.Value.ToUniversalTime() ?? model.SanctionExpires;

I get the following error ...

Operator

'??' cannot be applied to operands of type 'datetime' and 'DateTime'

I thought this should work, because I set the date property to nullable and this post assumes it should work too. What am I doing wrong?

UPDATE

, null-coaslescing Dapper, DateTime . NULL datetime. , , , ...

p.Add("@SanctionExpires", model.SanctionExpires.Value.ToUniversalTime() ?? model.SanctionExpires);

, UTC, SQL Azure, UTC , 11 ( ), . sql .

, , . ...

if (model.SanctionExpires == null)
    p.Add("@SanctionExpires", model.SanctionExpires);
else
    p.Add("@SanctionExpires", model.SanctionExpires.Value.ToUniversalTime());
+4
2

.Value nullable , . , - .

, , , , :

DateTime test = (model.SanctionExpires ?? DateTime.Now).ToUniversalTime();

: :

DateTime? test = model.SanctionExpires?.ToUniversalTime();
+9

GetValueOrDefault , DateTime NULL. , DateTime.Now.

, :

var defaultDateTime = DateTime.Now;
var dateTime = model.SanctionExpires.GetValueOrDefault(defaultDateTime).ToUniversalTime();

GetValueOrDefault , default(DateTime), DateTime null

var dateTime = model.SanctionExpires.GetValueOrDefault().ToUniversalTime(); //dateTime == default(DateTime) in case !model.SanctionExpires.HasValue

# 5.0 , , NULL # 6.0.

p.Add("@SanctionExpires", !model.SanctionExpires.HasValue ? null : (DateTime?)model.SanctionExpires.Value.ToUniversalTime());
0

Source: https://habr.com/ru/post/1661850/


All Articles