【问题标题】:InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Single'InvalidCastException:无法将“System.Double”类型的对象转换为“System.Single”类型
【发布时间】:2020-12-02 09:56:55
【问题描述】:

我正在尝试在 ASP.NET 中获取食物列表。我创建了一个模型 Menu 和一个模型 listMenu 来获取 Menucontroller 中的列表。我有以下代码,我得到这个 error:InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Single'。

我不知道问题是否出在数据库端,是否不是从表中读取

菜单控制器:

public async Task<IActionResult> Index(string searchString)
{               
    var foods = from m in _context.Menu
                            select m;
    
    if (!string.IsNullOrEmpty(searchString))
    {
        foods = foods.Where(s => s.Name.Contains(searchString));
    }
    var foodlist = new ListMenu
    {
        Foods = await foods.ToListAsync()
    };
    
    return View(foodlist);
}

菜单模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
    
namespace Resto.Models
{
    public class Menu
    {
        [Key]
        public string Name { get; set; }
    
        public float Price { get; set; }
    }
}

ListMenu 模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
    
namespace Resto.Models
{
    public class ListMenu
    {
        public List<Menu> Foods { get; set; }
        public string SearchString { get; set; }
    }
}

【问题讨论】:

  • Razor 页面标记和堆栈跟踪会很好。

标签: asp.net-core asp.net-core-mvc


【解决方案1】:

InvalidCastException:无法将“System.Double”类型的对象转换为 输入“System.Single”。

此问题与 C# 数据类型和 SQL Server 列数据类型不匹配有关。

下表列出了 C# 数据类型与 SQL Server 列数据类型之间的映射。

根据您的代码,由于 Menu 的 Price 属性是 float 类型,如果您在 SQL 数据库中使用 float 类型,它将显示“无法将类型为 'System.Double' 的对象转换为类型'System.Single'”错误。

为解决此错误,尝试将菜单表价格列数据类型更改为real(在模型中,使用浮点数据类型),

或者,将 Menu 模型的 Price 属性数据类型更改为 Double(在数据库中,您可以使用浮点列数据类型)。

public class Menu
{
    [Key]
    public string Name { get; set; }
    public double Price { get; set; }
}

【讨论】:

    【解决方案2】:

    Zhi Lv 的回答是正确的,但是 SQL 对浮点数有两种不同的精度级别,可以转换为两种不同的 C# 数据类型。 float 默认为 'float(53)' 并匹配 C# 'double'。 但是,SQL 'float(24)' 转换为 C# 'float'。因此,在您的情况下,您希望您的 SQL 类型为“float(24)”(或者如 Zhi 所说,将您的 C# 更改为 double)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 2011-07-11
      相关资源
      最近更新 更多