【发布时间】:2015-05-22 05:03:27
【问题描述】:
我一直试图弄清楚如何为 EF7(Beta 4)设置小数精度,但没有成功。
我期待做类似的事情:
modelBuilder.Entity<SomeClass>().Property(p => p.DecimalProperty).Precision(10, 6)
这似乎不可用,但我能够在 GitHub 的存储库中找到以下类:
没有使用 RelationalTypeMapping 类或方法签名的示例。也许这只是用作检索信息的映射 api 的一部分?
我可能期望的另一个地方如下:
modelBuilder.Entity<SomeClass>().Property(p => p.DecimalProperty).ForRelational().ColumnType()
或
modelBuilder.Entity<SomeClass>().Property(p => p.DecimalProperty).ForSqlServer().ColumnType()
这些只需要一个字符串,是这个功能还没有实现还是我没有找到正确的地方?
编辑:刚刚意识到 string 可能是 .ColumnType("decimal(10,6)") 类型的解决方案,直到进一步构建,但仍然不介意得到一些澄清因为我不想为此使用字符串
编辑:在得到 bricelam 的澄清后,我最终创建了以下扩展程序以供现在使用以避免使用字符串,我很欣赏他们的方法的简单性:
public static RelationalPropertyBuilder DecimalPrecision(this RelationalPropertyBuilder propertyBuilder, int precision, int scale)
{
return propertyBuilder.ColumnType($"decimal({precision},{scale})");
}
使用示例:
modelBuilder.Entity<SomeClass>().Property(p => p.DecimalProperty).ForRelational().DecimalPrecision(10,6);
编辑:对 RC1 进行修改
我还没有对这些进行测试,但我只是将以下 2 个样本放在一起,看看 RC1 可能会是什么样子
public static PropertyBuilder DecimalPrecision(this PropertyBuilder propertyBuilder, string precision, string scale)
{
return propertyBuilder.HasColumnType($"decimal({precision},{scale})");
}
public static PropertyBuilder SqlDecimalPrecision(this PropertyBuilder propertyBuilder, string precision, string scale)
{
return propertyBuilder.ForSqlServerHasColumnType($"decimal({precision},{scale})");
}
由于我还没有尝试过,我不确定“HasColumnType”或“ForSqlServerHasColumnType”之间的正确用法,但希望这会为某人指明正确的方向。
【问题讨论】:
-
由于我所有的小数属性都具有相同的精度,有什么方法可以在一行中对所有这些属性进行实现吗?我在 EF6 中使用它:
modelBuilder.Properties<decimal>().Configure(x => x.HasPrecision(18, 6)); -
@reala valoro,我已经更新了细节以反映 RC1 的变化