Well,EF doesn't have yet a good support for default values. Apparently this is something that EF 7 is going to have a better support due to the community has been requesting this some time ago.
I have already mapped your table using EF Power Tools and the configuration class that was generated was this:
public class PostMap : EntityTypeConfiguration<Post>
{
public PostMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Content)
.IsRequired();
this.Property(t => t.Title)
.IsRequired()
.HasMaxLength(200);
// Table & Column Mappings
this.ToTable("Posts");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Content).HasColumnName("Content");
this.Property(t => t.Title).HasColumnName("Title");
this.Property(t => t.Created).HasColumnName("Created");
}
}
As you can see the Created
column was not mapped as required, and if you don't set that property, EF will going to throw an exception because that column will attempt to update with default(DateTime)
wich is {1/1/0001 12:00:00 AM}
and the type of that column is datetime
(more details in this post).Even if you change the type of that column to datetime2
, you are not going to have the behavior that you are expecting.
If you want a property with a default value, you could resolve that problem setting the property in the entity's contructor:
public class Post
{
public int Id {get;set;}
[Required]
public DateTime Created{get;set;}
public Post()
{
Created=DateTime.Now;
}
}