I am working on an MVC 3 application in C# that is having trouble updating an entry in the table.
The update string that is being called from EF is sending in the date as such (all other values in the where statement have been removed for clarity):
where [CreateDate] = '2012-09-24 19:12:08'
The actual database entry has the date and the sql data type is datetime2(7):
2012-09-24 19:12:08.6457698
When the code is executed the dates don’t match and nothing is updated. I created my models using Reverse Engineering Code First from existing database. Here is my Model:
public class NPost
{
[HiddenInput(DisplayValue = false)]
public int NPostID { get; set; }
[HiddenInput(DisplayValue = false)]
public System.Guid UserId { get; set; }
[Required(ErrorMessage = "Please enter a title!")]
[StringLength(Int32.MaxValue)]
public string Title { get; set; }
[AllowHtml]
[Required(ErrorMessage = "Please enter the body of the post!")]
[StringLength(Int32.MaxValue)]
public string Body { get; set; }
[Required(ErrorMessage = "Please enter at least one tag!")]
[StringLength(Int32.MaxValue)]
public string Tags { get; set; }
public System.DateTime CreateDate { get; set; }
public Nullable<System.DateTime> PublishDate { get; set; }
public Nullable<double> Rating { get; set; }
[Required(ErrorMessage = "Please enter a topic!")]
[StringLength(Int32.MaxValue)]
public string Topic { get; set; }
[StringLength(Int32.MaxValue)]
public string TitleImage { get; set; }
[StringLength(Int32.MaxValue)]
public string ListingImage { get; set; }
[StringLength(Int32.MaxValue)]
public string BoxImage { get; set; }
public virtual aspnet_Users aspnet_Users { get; set; }
}
What do I need to do to get these dates to line up and work correctly?
I agree with the cautions that others have expressed regarding what you’re doing here. However, we ought to have a direct answer to your question too! I suspect that EF is treating your column as a SQL
datetimevalue rather than the newerdatetime2type. So try the following.You can use the
[Column(TypeName = "datetime2")]attribute on your property to indicate the exact database type to use, or theHasColumnTypemethod if you prefer fluent configuration.