无法将十进制类型转换为double

时间:2016-12-30 21:20:03

标签: c# entity-framework linq web-services

我有一个简单的Web服务通过实体框架调用sql视图表。我可以将字符串中的所有列设置为精细但不是数字中的列,如SQL中的UID_NUM(numeric(38,8),null)。我有AddressALL类来设置如下所示的列,并在LINQ中的p.UID_NUM错误输出。

public class GISAddressWebService : System.Web.Services.WebService
{
     [WebMethod]
     public AddressALL[] getAddress()
     {
         try
         {
             List<view_COBADDRESS> address = new List<view_COBADDRESS>();
             using (GISAddressEntities database = new GISAddressEntities())
             {
                 return database.view_COBADDRESS
                        .Where(p => p.UNIT_NUM == "103")
                        .Select(p => new AddressALL { UID_NUM = p.UID_NUM, ADD_FULL = p.ADD_FULL, POSTALCITY = p.POSTALCITY, ZIP5 = p.ZIP5}).ToArray();
             }
         }
         catch (Exception)
         {
             return null;
         }
     }
}

public class AddressALL
{
     public double UID_NUM { get; set; }
     public string TLID { get; set; }
     public string ADD_FULL { get; set; }
     public string POSTALCITY { get; set; }
     public string STATE { get; set; }
     public string ZIP5 { get; set; }
     public string IN_OUT { get; set; }

}

3 个答案:

答案 0 :(得分:1)

return database.view_COBADDRESS
                        .Where(p => p.UNIT_NUM == "103")
                        .Select(p => new AddressALL { UID_NUM = System.Convert.ToDouble(p.UID_NUM), ADD_FULL = p.ADD_FULL, POSTALCITY = p.POSTALCITY, ZIP5 = p.ZIP5}).ToArray();

MSDN

答案 1 :(得分:1)

显而易见的解决方案,而不是

.Select(p => new AddressALL
        {
            UID_NUM = p.UID_NUM,
            ADD_FULL = p.ADD_FULL,
            POSTALCITY = p.POSTALCITY,
            ZIP5 = p.ZIP5
        });

.Select(p => new AddressALL
        {
            UID_NUM = Convert.ToDouble(p.UID_NUM),
            ADD_FULL = p.ADD_FULL,
            POSTALCITY = p.POSTALCITY,
            ZIP5 = p.ZIP5
        });

在您的选择语句.Select(p => new AddressALL{ ... })中,您正在尝试projection尝试为每个AddressALL选择p类型的新对象,并且您正在使用该对象初始化程序语法{...},以使源对象p的属性与目标类型AddressALL的属性相匹配。

但是,您的错误消息表明您的p.UID_NUM类型为decimal,而UID_NUM上的AddressALL属性属于double类型。因此,您必须将值转换为必要的目标类型。

答案 2 :(得分:1)

十进制数字比双数字更有意义,因此它可以更精确,并且还占用更多的内存。由于这种差异,必须通过(双)p.UID_NUM明确地编程这种类型的改变。