Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting DateTime to SmallDateTime in c#

How can ı convert datetime to smalldatetime in c# ? I'm taking the date and ı need to convert it to be accordance with database. It is forbidden to change the datatype of column in sql.

like image 262
kapozade Avatar asked Jun 05 '13 16:06

kapozade


People also ask

How do I convert datetime to Smalldatetime?

Example: DECLARE @thedate date SET @thedate = '2020-12-01' SELECT @thedate AS 'date', DATEADD(nanosecond, 7, CAST(@thedate AS smalldatetime)) AS 'smalldatetime'; Result: The datepart nanosecond is not supported by date function dateadd for data type smalldatetime.

What is the maximum date value that can be stored in Smalldatetime?

smalldatetime description YYYY is four digits, ranging from 1900, to 2079, that represent a year.


1 Answers

You can use the .NET DateTime type for your entity framework model, but tell EF that it uses a non-default column type in the database. You do this by overriding the OnModelCreating method of your DbContext, and using the HasColumnType method:

public class Foo    
{
    public int Id { get; set; }
    public DateTime IAmSoSmall { get; set; }    // wants to be smalldatetime in SQL
}

public class MyContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var foo = modelBuilder.Entity<Foo>();
        foo.Property(f => f.IAmSoSmall).HasColumnType("smalldatetime");

        base.OnModelCreating(modelBuilder);
    }
}

Of course, you'll have to do the appropriate range-checking on your DateTime property to be sure that the stored values fall between those supported by SQL's smalldatetime. I guess you could do that with a property attribute like:

    [Range(typeof(DateTime), "1/1/1900", "6/6/2079")]
    public DateTime IAmSoSmall { get; set; }    // wants to be smalldatetime in SQL

...based on a valid range from January 1, 1900, through June 6, 2079, as documented on MSDN.

like image 109
Myk Willis Avatar answered Sep 20 '22 14:09

Myk Willis