实体框架:将db real映射到十进制?无法将System.Single转换为System.Double

时间:2017-05-24 19:10:41

标签: c# entity-framework entity-framework-6

我有一个包含以下字段的表:

dbo.AccountProbability

StageKey (binary(16), not null)
AccountId (int, not null)
Probability (real, null)
IsCurrent (bit, not null)

它在实体框架中映射如下:

[Table("dbo.AccountProbability")]
public partial class AccountProbability
{
    [Required]
    [MaxLength(16)]
    public byte[] StageKey { get; set; }

    public int AccountId { get; set; }

    public double? Probability { get; set; }

    public bool IsCurrent { get; set; }
}

当我尝试将其映射到对象时,在下面的方法中,我收到错误:

public async Task GetAccountProbabilities()
{
    var repo = GetDatabaseRepo();
    var validAcctProbs = repo.Where<AccountProbability>(
                    m => m.IsCurrent).ToList();
}


private static IDatabaseRepository GetDatabaseRepo()
{
    var context =
        new DbContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
    return new DatabaseRepository(context);
}

validAcctProbs将其列入清单时失败,错误为:The 'Probability' property on 'AccountProbability' could not be set to a 'System.Single' value. You must set this property to a non-null value of type 'System.Double'.

我相信TSQL中的实数是EF的两倍。

编辑:我不相信这是一个骗局,因为上一个问题是关于SQLite和该驱动程序中的错误映射。这适用于Microsoft TSQL。

1 个答案:

答案 0 :(得分:1)

  

我认为TSQL中的实数是EF的两倍

文档对此有点含糊不清。我们需要在实现中查找它。 source code of EF6是公开的,因此我们发现:

<Type Name="tinyint" PrimitiveTypeKind="Byte"></Type> 
<Type Name="smallint" PrimitiveTypeKind="Int16"></Type> 
<Type Name="int" PrimitiveTypeKind="Int32"></Type> 
<Type Name="bigint" PrimitiveTypeKind="Int64"></Type> 
<Type Name="float" PrimitiveTypeKind="Double"></Type> 
<Type Name="real" PrimitiveTypeKind="Single"></Type> 
<Type Name="decimal" PrimitiveTypeKind="Decimal"> 

让我说明为什么这是有道理的:

  1. 在T-SQL中,从SQL Server 2008开始,real为float(24)是一个4字节(32位)的浮点数。
  2. 在.NET中,Singlefloat是一个4字节(32位)的浮点数。
  3. 在.NET中,Double是一个8字节(64位)的浮点数。
  4. real的范围:-3.40e38至3.40e38
    范围Single:-3.402823e38至+ 3.402823e38

    因此double?字段使用Probability类型毫无意义,因为real永远不会耗尽Single的精确度。