c# - 在 C# 中将 DateTime 转换为 SmallDateTime

标签 c# asp.net entity-framework

如何在 C# 中将 datetime 转换为 smalldatetime?我正在获取日期,我需要将其转换为与数据库一致。禁止在sql中改变列的数据类型。

最佳答案

您可以为您的 Entity Framework 模型使用 .NET DateTime 类型,但告诉 EF 它在数据库中使用非默认列类型。为此,您可以覆盖 DbContext 的 OnModelCreating 方法,并使用 HasColumnType 方法:

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 所支持的值之间。我猜你可以用像这样的属性来做到这一点:

    [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 中所述。

关于c# - 在 C# 中将 DateTime 转换为 SmallDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16945111/

相关文章:

c# - 使用 Entity Framework 保存对子集合的更改

c# - 存储库、删除对象、模型与 ID

c# - 仅适用于 GET 方法的全局查询过滤器

c# - 什么支持Excel更好? (VB.net 或 C#.net ??)

c# - C#动态创建Type数组

asp.net - using 语句是否阻止我关闭或销毁对象?

asp.net - 我可以将 asp.net 放在 css 中吗?

c# - 如何使用 MVP 中的模型填充数据 GridView

c# - DB2 iSeries AS400 - 数据库连接

mysql - EF Fluent API - 检索相关实体