An extraordinary release of Datetime using LINQtoSQL

It really bothers me. Here is a snippet of my model:

* SQL Server *

Event
-----
Id (int, PK) NOT NULL
Title (varchar(100)) NULL
LastModified (datetime) NULL

EventDates
----------
Id (int, PK) NOT NULL
StartDate (datetime) NULL
EndDate (datetime) NULL

* C# *

Event
-----
public int Id
public string Title
public DateTime LastModified

EventDates
----------
public int Id
public DateTime StartDate
public Datetime EndDate

The field LastModifiedhas been in the database since its creation. I save its value when I save an event, but I want to display it in a table, so I changed my Event GetEventsreturn repository

:
return (from e in GetDbEvents()
                select new Event
                {
                    // Miscellaneous fields..
                    LastModified = e.LastModified.GetValueOrDefault() // Shiny new code
                });

When I call it, I scream:

The conversion of a char data type to a datetime data type 
resulted in an out-of-range datetime value.

If I split the above code into this, it still won't help, and I get the same error if I try to list the result:

var test = (from e in _db.Events
                    select e.LastModified.GetValueOrDefault());

As a test, I made the same statement for my table EventDates(again, with two datetime columns):

 var test4 = (from ed in _db.EventDates
                     select new EventDate
                     {
                         StartDate = ed.StartDate.GetValueOrDefault(),
                         EndDate = ed.EndDate.GetValueOrDefault()
                     });

This works great, of course. There are no errors when listing, all values ​​are correct.

, LastModified Events NULL, EventDates .

- ? !

: Events , EventDates - , ?

+3
4

GetValueOrDefault(). DateTime.MinValue (01-01-0001) " ", sqlserver ( 1753).

Nullable<DateTime>, sql null, .

+4

# LastModified public DateTime? LastModified, . , .

+1

?

( LastModified DateTime?, , .Value ..), DateTime?, DateTime . :

return from e in GetDbEvents()
       select new Event(e.LastModified);

...

//In Event class:
public Event(DateTime? lastModified)
{
    LastModified = lastModified.GetValueOrDefault();
}

, GetValueOrDefault() , SQL.

, ...

+1

, , /WHERE, SELECT:

GetValueOrDefault(). LINQ to SQL ( IMO) SQL, COALESCE ( ISNULL), :

COALESCE(LastModified, '1/1/0001 12:00:00 AM')

, datetime datetime SQL Server 1753 . SQL Server LINQ to SQL, .

Nullable, SQL Server . GetValueOrDefault(), , , :

  1. LastModified.GetValueOrDefault(System.Data.SqlTypes.SqlDateTime.MinValue.Value)
  2. LastModified.HasValue && LastModified > DateTime.Now
0

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


All Articles