0

I work on a big ASP.NET MVC application. This app contains many forms with date time controls. Values of this controls is optional. Also in database field where store values from this controls can be null. Date-time controls returns Min date (0001/1/1) if users not fill it. I'm see often next exceptions in logs The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. I know how fix it For example. Before fix:

DecisionOfLiquidationData= model.DecisionOfLiquidationData,
CompletionOfLiquidationData = model.CompletionOfLiquidationData

After fix:

DecisionOfLiquidationData= model.DecisionOfLiquidationData==DateTime.MinValue ? null: model.DecisionOfLiquidationData,
CompletionOfLiquidationData = model.CompletionOfLiquidationData == DateTime.MinValue ? null : model.DecisionOfLiquidationData

But application contains many code that's look like before fix. My question is next. Is any way to decide this problem globally using web.config or global.asax? Which ideas?

user6408649
  • 1,227
  • 3
  • 16
  • 40

2 Answers2

2

My suggestion is to add a default value to the constructor for your model objects to set the value you want as default.

E.g.

public MyDbEntity()
{
    myDateProperty = new DateTime(1900,1,1);
}

This could be quite a bit of typing if you have a lot of model objects with DateTimes that need to be changed, but at least you will only need to do it once per object, and then your done.

Edit: Note that when using Model First Entity Framework, that you will have to create a partial class and declare the constructor there in order to avoid losing your changes when the model code is regenerated.

Brandon Kramer
  • 1,098
  • 6
  • 7
0

you can use nullable ? with datetime like

public DateTime? DecisionOfLiquidationData {get;set;}

what it will do is set the value to default null if no value is assigned

Usman
  • 4,615
  • 2
  • 17
  • 33