I\'m using the DbContext and Code First APIs introduced with Entity Framework 4.1.
The data model uses basic data types such as string
Simple. On your code first, set the type of DateTime to DateTime?. So you can work with nullable DateTime type in database. Entity example:
public class Alarme
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? DataDisparado { get; set; }//.This allow you to work with nullable datetime in database.
public DateTime? DataResolvido { get; set; }//.This allow you to work with nullable datetime in database.
public long Latencia { get; set; }
public bool Resolvido { get; set; }
public int SensorId { get; set; }
[ForeignKey("SensorId")]
public virtual Sensor Sensor { get; set; }
}
My solution was to switch all datetime columns to datetime2, and use datetime2 for any new columns. In other words make EF use datetime2 by default. Add this to the OnModelCreating method on your context:
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
That will get all the DateTime and DateTime? properties on all your entities.
initialize the Start property in the constructor
Start = DateTime.Now;
This worked for me when I was trying to add few new fields to the ASP .Net Identity Framework's Users table (AspNetUsers) using Code First. I updated the Class - ApplicationUser in IdentityModels.cs and I added a field lastLogin of type DateTime.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
CreatedOn = DateTime.Now;
LastPassUpdate = DateTime.Now;
LastLogin = DateTime.Now;
}
public String FirstName { get; set; }
public String MiddleName { get; set; }
public String LastName { get; set; }
public String EmailId { get; set; }
public String ContactNo { get; set; }
public String HintQuestion { get; set; }
public String HintAnswer { get; set; }
public Boolean IsUserActive { get; set; }
//Auditing Fields
public DateTime CreatedOn { get; set; }
public DateTime LastPassUpdate { get; set; }
public DateTime LastLogin { get; set; }
}
If your DateTime
properties are nullable in the database then be sure to use DateTime?
for the associated object properties or EF will pass in DateTime.MinValue
for unassigned values which is outside of the range of what the SQL datetime type can handle.
In case anyone is as dopey as me, double check the year of your date. I was converting a date from a text file in YYMMDD format so was creating a date with a year of 0020, not 2020. Obvious error but I spent more time looking at it but not seeing it than I should have!
In my case this happened when I used entity and the sql table has default value of datetime == getdate(). so what I did to set a value to this field.