I am using new way of seeding data in Entity Framework 2.1:
modelBuilder.Entity<Blog>().HasData(new Blog {BlogId = 1, CreateDate = DateTime.Now});
However, applying this to the database throws an exception Conversion failed when converting date and/or time from character string
. I can see that in the generated SQL the value comes as '2018-06-01T13:22:13.248-07:00'
which is wrong. And since the field is obviously DateTime
, I can't format it into the string the way I would want to.
Is it a bug in EF? Or I am missing something obvious? In the traditional EF code it works fine:
Blog.CreateDate = DateTime.Now;
...
context.SaveChanges();
Or maybe there is some workaround on the SQL side that would allow it to take date in this format?
Issue 1 here is the conversion failure. This can be solved by converting the column to DateTime2. Reference: Seeding DateTime in EF 2.1 throws exception #12211
Issue 2 (DateTime.Now becomes a fixed date/time) is something I looking into as well.
Use {[Column(TypeName = "datetime")] annotation
public class Blog
{[Column(TypeName = "datetime")]
public DateTime CreateDate { get; set; }