Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store only date in database not time portion C#

I have a test class and an ExecutionDate property which stores only date but when we use [DataType(DataType.Date)] that also stores the time portion in database but I want only date portion.

public class Test {      [Key]      public int Id { get; set; }       [DataType(DataType.Date)]      public DateTime ExecutionDate { get; set; }       } 

Is any way to store only date on time portion in db using Entity Framework? Please help me....

I have added snapshot when use [DataType(DataType.Date)] that stores time portion 00:00 I want remove that

enter image description here

like image 415
KARAN Avatar asked Nov 17 '15 16:11

KARAN


People also ask

Which data type can store only date and time?

Datetime and Interval Data Types. The datetime data types are DATE , TIMESTAMP , TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE . Values of datetime data types are sometimes called datetimes. The interval data types are INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND .

How should I store dates in database?

MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.


2 Answers

I think you are trying to specify database column type. You could use data annotations as described in this article.

Here is an example :

[Table("People")] public class Person {     public int Id { get; set; }      [Column(TypeName = "varchar")]     public string Name { get; set; }      [Column(TypeName="date")]     public DateTime DOB { get; set; } } 

By default, string is translated to nvarchar, we have changed that here. Also Datetime (this is what you asked I suppose) which by default maps to datatime in sql server, is changed to date which stores only the date portion and not the time portion of a DateTime value.

like image 195
Ravi M Patel Avatar answered Sep 22 '22 11:09

Ravi M Patel


On EF core one may add override OnModelCreating in DbContext class.

protected override void OnModelCreating(ModelBuilder builder)         {             builder.Entity<Test>().                 Property(p => p.ExecutionDate)                 .HasColumnType("date");         } 
like image 42
Lapenkov Vladimir Avatar answered Sep 23 '22 11:09

Lapenkov Vladimir