嗯,有趣!当我使用带有以下内容的表创建一个简单的数据库模型时DateTime
列,实体框架默认创建一个 SQL DateTime 类型的列,而不是 DateTime2。我使用EntityFramework版本6.1.3
class Blog
{
public int Id {get; set;}
public DateTime IntroductionDate {get; set;}
}
Sql Server Management Studio 报告该列IntrdductionDate
有属性(datetime, not null)
.
不管怎样,不久前我遇到了一个问题,我希望每个 DateTime 都被建模为dateTime2
代替datetime
。我想你可以使用类似的方法来强制列使用datetime
class MyDbContext : DbContext
{
DbSet<...> ...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Configure that all used DateTime should be modeled datetime2:
const string standardDateTimeType = "datetime2";
modelBuilder.Properties<DateTime>()
.Configure(p => p.HasColumnType(standardDateTimeType);
...
}
您可以将其用于您想要建模的所有类型。例如,如果您想建模所有小数都具有相同的精度和小数位数:
byte standardDecimalPrecision = 19;
byte standardDecimalScale = 8;
modelBuilder.Properties<decimal>()
.Configure(p => p.HasPrecision(standardDecimalPrecision, standardDecimalScale));
当然,您可以使用设置列的类型ColumnAttribute
数据注释,但这会迫使您对每个 DateTime 执行此操作,并且可能会出现未来的类会忘记这一点的错误。