实体框架:将数据库真实映射到小数?无法转换System.Single以System.Double

问题描述:

我有一个表具有以下字段:实体框架:将数据库真实映射到小数?无法转换System.Single以System.Double

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

单个不是整数(单精度浮点,与'float'相同)。但tsql'real'映射到.NET'double'是正确的:[映射](https://msdn.microsoft.com/en-us/library/bb896344(v = vs.110).aspx) – dlatikay

+0

可能[为什么“real”和“float”都被映射为“Single”而不是“Double”?](https://*.com/questions/21002246/why-both-real-and-float-get-映射到单代替-的双) – dlatikay

I believe that reals in TSQL are doubles in 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位)浮点数。

real范围:-3.40e38到3.40e38
范围Single:-3.402823e38至+ 3.402823e38

所以有使用double?类型,请​​场没有意义的,因为real永远不会耗尽Single的精度。