entity-framework-core - Entity Framework 7 为模型构建器设置小数精度

标签 entity-framework-core

我一直试图弄清楚如何为 EF7(Beta 4)设置小数精度,但没有运气。

我期待做这样的事情:

modelBuilder.Entity<SomeClass>().Property(p => p.DecimalProperty).Precision(10, 6)

这似乎不可用,但我能够在 GitHub 的存储库中找到以下类:

https://github.com/aspnet/EntityFramework/blob/7.0.0-beta4/src/EntityFramework.Relational/RelationalDecimalTypeMapping.cs

没有使用 RelationalTypeMapping 类或方法签名的示例。也许这只是用作检索信息的映射 api 的一部分?

我可能期望的另一个地方如下:
modelBuilder.Entity<SomeClass>().Property(p => p.DecimalProperty).ForRelational().ColumnType() 

或者
modelBuilder.Entity<SomeClass>().Property(p => p.DecimalProperty).ForSqlServer().ColumnType()

这些只需要一个字符串,是这个功能还没有实现还是我只是没有找对地方?

编辑:刚刚意识到字符串可能适用于 .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”之间哪个是正确的用法,但希望这会指向正确的方向。

最佳答案

您的解决方法是我们想要的设计。您可以设置精度、比例、最大长度、unicode/ansi、固定/可变长度等类型,而不是一堆“方面”。我们决定保持简单:如果默认类型映射不是什么你想要,告诉我们使用什么类型。已经有关于重新考虑这一决定并重新引入“方面”的讨论。如果你对此有强烈的感觉,我会鼓励你create a new issue .

另请注意,目前类型映射中还有许多其他错误,但它们应该会在我们发布 beta5 时修复。

关于entity-framework-core - Entity Framework 7 为模型构建器设置小数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388695/

相关文章:

c# - EF Core 修改后的实体状态如何表现?

c# - 如何在 EF Core 中创建 DbContext 实例时传递 DbContextOptions 值

postgresql - 使用 EF Core 5 查询 Postgres Json 字段

c# - 在 Entity Framework Core 中编写实体 POCO 类的正确方法是什么?

c# - 使用 Entity Framework Core 调用标量函数的最佳实践 (2.1)

asp.net-core - 如何解决 ASP.NET Core Web API 子对象创建问题?

c# - 使用前是否应检查 .NET EF Core DbContext 属性为 null

azure - 无法使用 Microsoft.EntityFrameworkCore.Cosmos 连接到 Azure Cosmos Db 帐户 - 响应状态代码

asp.net-core - 为 EF Core 数据种子创建 dotnet 工具

asp.net-core - 使用 Include 进行 EF Core 联接,但外键不是另一个表上的主键