EntityFramework异常The specified cast from a materialized 'System.Double' type to the 'System.Single' type is not valid.

时间:2021-04-16 09:15:56

实体类:

    public class ReportEntity
{
public string FactorName { get; set; }
public double MaxVal { get; set; }
public double MinVal { get; set; }
public double AvgVal { get; set; }
public string UpdateTime { get; set; }
public string Unit { get; set; }
public int DecimalDigit { get; set; }
}

SQL语句

            string sqlstr = "   select b.FactorName,cast(MAX(a.Val) as float) as MaxVal,cast(MIN(a.Val) as float) as MinVal,cast(AVG(a.Val) as float) as AvgVal,"
+ strTime + " as UpdateTime,b.Unit,b.DecimalDigit "
+ " from Instrument_Data a,Factor b "
+ " where a.UpdateTime between '" + dtBegin + "' and '" + dtEnd + "' "
+ " and a.FactorID = b.FactorID "
+ " group by b.FactorName,b.Unit, " + strTime + ",b.DecimalDigit "
+ " order by b.FactorName,b.Unit," + strTime + ",b.DecimalDigit "; using (var db = new DAL.WSIPCContext())
{
var result3 = db.Database.SqlQuery<Entity.ReportEntity>(sqlstr);
this.lsvData.Items.Clear();
foreach (Entity.ReportEntity i in result3)
{
ListViewItem item = new ListViewItem();
item.SubItems.Clear();
item.Text = i.UpdateTime;
item.SubItems.Add(i.FactorName);
string format = "#0.".PadRight(i.DecimalDigit + 3, '0');
item.SubItems.Add(i.MaxVal.TryToDoubleStr(format));
item.SubItems.Add(i.MinVal.TryToDoubleStr(format));
item.SubItems.Add(i.AvgVal.TryToDoubleStr(format));
item.SubItems.Add(i.Unit);
this.lsvData.Items.Add(item);
}
}

将double换成float出现错误。EF使用System.Double对应SQLServer中的float。

重点关注:此处对SQL语句的结果也有要求,结果必须转换为float,才能与实体类映射成功!