Search code examples
asp.netdotvvm

DateTime? to DateTime


I am stuck. I'm creating a database of authors and run to a problem. I need to save value Umrti (date of death) to database as null, but it always save that value as 01.01.0001. I tried few things and now my code looks like this:

    public class AutorDetailModel
{
    public int Id { get; set; }
    [Required]
    public string Jmeno { get; set; }
    [Required]
    public string Prijmeni { get; set; }
    public string ProstredniJmeno { get; set; }
    [DotvvmEnforceClientFormat]
    public DateTime Narozeni { get; set; }
    [DotvvmEnforceClientFormat]
    public DateTime? Umrti { get; set; }
    public string Bio { get; set; }
    public string Narodnost { get; set; }
    public byte Obrazek { get; set; }
}

And in service like this:

        public async Task UpdateAutorAsync(AutorDetailModel autor)
    {
        using (var dbContext = CreateDbContext())
        {
            var entity = await dbContext.Autors.FirstOrDefaultAsync(s => s.Id == autor.Id);

            entity.Jmeno = autor.Jmeno;
            entity.Prijmeni = autor.Prijmeni;
            entity.ProstredniJmeno = autor.ProstredniJmeno;
            entity.Narozeni = autor.Narozeni;
            entity.Umrti = autor.Umrti;
            entity.Bio = autor.Bio;
            entity.Narodnost = autor.Narodnost;
            entity.Obrazek = autor.Obrazek;


            await dbContext.SaveChangesAsync();
        }
    }

However, autor.Umrti still gives me this error:

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

I am really stuck and will appreciate any advice. Thanks

And sorry for my bad english :)


Solution

  • If you're using SQL Server (possibly other Database engines too) then you can't save a NULL value in a DateTime field.

    You'll have to convert the NULL to a date, any date, to save it in the db. Typically SQL Server uses '1900-01-01' to represent a NULL date. In most cases that's fine as, unless you are working with historical data around the end of the 18th Century, it won't clash with your valid data. When reading from the db you can convert all dates with a value of '1900-01-01' to null in your code, and when writing to the db if the value in code is null convert it to '1900-01-01'.