I'm using ASP.NET Boilerplate MVC (not Core) template in my project, which uses EF6 as ORM. Database is SQL Server Express.
Here's my entity object (ignoring non-related properties):
public class Asset : AggregateRoot<long>
{
[DataType(DataType.DateTime)]
public DateTime? LastControlTime { get; set; }
}
When I create a new Asset, this field appropriately created as NULL. So, everything works as intented at first. But when I try to update an object with a simple service call, it screws up.
Here's the method in the application service class:
public void ResetLastControlTime (EntityDto<long> input)
{
var asset = Repository.Get(input.Id);
asset.LastControlTime = default(DateTime?);
}
This should reset that field to null. I also tried asset.LastControlTime = null;
. But in the end it's written "0001-01-01 00:00:00.0000000" to that field in the database. I have lots of places in code that I control for a null value so now I had to change tons of old files or I must find some way to reset that field to simply NULL.
I checked similar questions here but cannot find an answer. All of them tells about nullable DateTime, which I already have. In SQL server table schema, Data Type is datetime2(7)
, so I guess that's correct too. Oh and deleting the DataType annotation also didn't change anything.
So what am I missing here? What should I check to find the issue?
CodePudding user response:
I suppose if all else fails, you can simplify most of your code by re-implementing the property:
public class Asset : AggregateRoot<long>
{
public DateTime? _LastControlTime;
[DataType(DataType.DateTime)]
public DateTime? LastControlTime {
get {
return _LastControlTime;
}
set {
if (value == DateTime.MinValue) {
_LastControlTime = null;
} else {
_LastControlTime = value;
}
}
}
It doesn't really cut to the heart of the problem, but will let you progress without having to change all of your == null and .HasValue throughout the entire program.