如何在 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/