在C#转换日期时间为smalldatetime [英] Converting DateTime to SmallDateTime in c#

查看:1526
本文介绍了在C#转换日期时间为smalldatetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能转换日期时间在c#为smalldatetime?我正在日期,我需要将其转换为符合数据库。禁止改变列的数据类型的SQL。

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.

推荐答案

您可以使用.NET的日期时间类型的实体框架模型,而是告诉EF,它使用非默认的字段类型在数据库中。您可以通过覆盖在 OnModelCreating 您的DbContext的方法,以及使用在 HasColumnType 方式做到这一点:

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);
    }
}

当然,你必须做你的DateTime属性适当范围检查,以确保存储的值那些SQL的支持SMALLDATETIME之间。我想你可以做到这一点与属性的属性,如:

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

...基于有效范围为1900年1月1日,到2079年6月6日,作为记录在MSDN上。

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

这篇关于在C#转换日期时间为smalldatetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆