【问题标题】:ASP.NET MVC : how to run a stored procedure using LINQ syntax?ASP.NET MVC:如何使用 LINQ 语法运行存储过程?
【发布时间】:2020-12-18 21:14:16
【问题描述】:

我正在尝试使用 Linq to Sql 来执行存储过程。直到今天我一直在使用以下语法,但从今天开始,它开始在整个应用程序中给我一个错误。我得到以下异常。

System.InvalidOperationException: 'The cast to value type 'System.Boolean' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.' 

我使用的代码

return db.Database.SqlQuery<SchViewModel>("TaskList.TaskListSchedule").ToList();
//View Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace TaskList.Models
{
    public class SchViewModel
    {
        public int TaskListItemID { get; set; }
        public Nullable<int> ReportID { get; set; }
        public Nullable<int> MemberID { get; set; }
        public string ReportName { get; set; }
        public string FrequencyType { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> DueDate { get; set; }
        public string Deadline { get; set; }
        public Nullable<int> Duration { get; set; }
        public string Day { get; set; }
        public string Name { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> CompletedDate { get; set; }
        public bool Missed { get; set; }
        public string OnTime { get; set; }
        public string Comments { get; set; }
    }
}

【问题讨论】:

  • 这取决于您使用的数据库访问技术,与Asp.Net MVC无关。
  • 直到今天我一直在使用以下语法,但从今天开始,它开始在整个应用程序中给我这个错误,并显示以下消息。 System.InvalidOperationException:“转换为值类型“System.Boolean”失败,因为具体化值为空。结果类型的泛型参数或查询必须使用可为空的类型。我使用的代码 - return db.Database.SqlQuery("TaskList.TaskListSchedule").ToList(); --- 我以为我用错了语法
  • 有什么建议为什么我会突然收到这个错误?或者修复一下?
  • @Ven 请发布SchViewModel 定义和它试图分配的一些示例数据。
  • 今天,Missednull 值的第一条记录进入了数据库。我想有人错过了……

标签: asp.net-mvc linq lambda


【解决方案1】:

如果布尔值为null,则需要检查存储过程中的布尔值,然后需要在SQL中使用以下条件。

ISNULL(字段, 0)

所以它会被转换成布尔类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2017-12-28
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多