I have the following Entity Framework query and that query has a DateTime
column called by
and it is obtained from MySQL, but sometimes it is NULL
, and I get an error
The specified conversion is invalid.
I know it is resolved turning my model like
public by? { get; set; }
but I don't want to make it nullable, I would like to know if there is an attribute such as [DefaultValue ()]
, which indicates that if a null is obtained, it will be converted to a default value, that is, a DateTime.MinValue
is inserted so as not to convert the nullable datetime
var Context = new Context();
var docs = Context.Docs.AsNoTracking()
.Where(d => d.froms == "active")
.FirstOrDefault();
The answer is no: Check available data annotations here. It is for core, but contains all EF 6 attributes as well.
It seems that EF makes a point of not allowing you to do that even with value conversions: https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions
A null value will never be passed to a value converter. This makes the implementation of conversions easier and allows them to be shared amongst nullable and non-nullable properties.
This makes sense, as you are effectively trying to bypass a configuration that you, yourself added to your project.
If it makes sense to have null values in your database, it should make sense for your code to have them too.
On any other (not null) case
Value converters allow property values to be converted when reading from or writing to the database.