Convert to default value when value is null in Entity Framework

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();

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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://docs.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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x