Hello, I have the following problem. In a sqlserver database I have an entity with datetime fields, I generated 2 new date fields and updated my model from the database. The fields were imported without problems, I add them to the corresponding class, and when doing the query it tells me:
Can't cast type System.DateTime? in System.DateTime , an explicit conversion already exists
This is how the fields that do work are declared:
public DateTime FechaCreacion {get;set;}
public DateTime FechaModif {get;set;}
And the ones I'm wanting to add:
public DateTime FechaAsign { get; set; }
public DateTime FechaCierre { get; set; }
And my Query:
query = (from q in _conexion.Ticket_Cab where [bla..bla..bla]
select new Ticket {[bla..bla] FechaCreacion = q.tik_fechacreacion,
FechaModif = q.tik_fechamodif, FechaAsign = q.tik_fechaAsign,
FechaCierre = q.tik_fechaCierre}).ToList();
The last two fields (q.tik_fechaAsign , q.tik_fechaCierre )
are underlined in red and it throws me the error that I quote above. Anyone know what might be happening?
Your problem occurs when assigning a value of type
Nullable<DateTime>
withDateTime
, currently, you declare the dates in the following way:DateTime
is a struct that cannot be assigned tonull
, I think the same goes for any struct.So you must declare the variable as a value capable of receiving
null
by value and you can do it in the following way 1 :Or in the "pretty" way :
This happens because in the declaration of the table in your database, the table accepts
null
by value in these fields.If you want the fields to be the same as the previous ones, you should try to add the clause
NOT NULL
in the definition of the table in your database.Note that by having a type in your class, you don't access the inner
Nullable<T>
member directly , but instead use the property of the object.DateTime
.Value
To access the actual value of the
DateTime
one you define in the query, you must do something like the following:Not to mention that you need to do a check
null
to check the current value of the field.Another alternative:
Instead of altering your class definition
Ticket
, you can just do a check on the query and it should work just fine, except that you won't have valuesnull
in the class, you can use a value like01/01/1865 00:00:00 AM
to represent a false value ornull
.The query would look like the following:
Where
01/01/1800
is the date indicating that your value is false ornull
.1 : You must do
using System;
when using this method.In your database, they can surely be nulls, which leads you to edit:
And if in case it throws you an error in the query
You repeat the same move in the next field
Where you use the data
q.tik_fechaAsign
andq.tik_fechaCierre
put.Value
it so that it is as follows:This is because
q.tik_fechaAsign
andq.tik_fechaCierre
are declared asDateTime?
, that is, they areNullable
, they may or may not contain a value and when using them it is required to put the value you are working with.