【问题标题】:Object reference not set to an instance of an object MVC 5对象引用未设置为对象 MVC 5 的实例
【发布时间】:2015-09-27 23:35:33
【问题描述】:

我是 MVC 的新手,从事 3 层 MVC 项目,我正在使用现成的数据库。

现在我需要在业务层中使用 linq 编写一个查询,以提供这样的医生列表:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DoctorsSheet.DataAccess;

namespace DoctorsSheet.Business
{
    class Doctor : IDoctor
    {
        DoctorsSheetDBEntities db = new DoctorsSheetDBEntities();

        public IQueryable<Doctors> GetDoctors()
        {
            var doctors = from d in db.Doctors
                          select d;

            return doctors.AsQueryable<Doctors>();
        }
     }
}

当我从 DoctorsController 调用 GetDoctors() 它告诉我对象引用未设置为对象的实例

这是控制器:

public ActionResult Index()
{
    var doctors = obj.GetDoctors().AsQueryable<Doctors>();
    return View(doctors);
}

请帮我解决一下。

【问题讨论】:

  • 您在哪个变量上收到此错误?
  • 在执行GetDoctors() 之后,您不需要转换为 Queryable,因为您已经在方法中转换为 Queryable。
  • 关于 ActionResult @ramiramilu 中的变量医生
  • @Sippy 如果你的意思是这样的话: var doctor = obj.GetDoctors();我做到了,但仍然无法正常工作
  • 您的控制器中的obj 是什么?

标签: asp.net-mvc 3-tier


【解决方案1】:

让你的班级public -

public class Doctor : IDoctor

然后如下图初始化obj变量,然后使用obj

IDoctor obj = new Doctor();

注意:正如@Sippy 所解释的,您无需使用GetDoctors().AsQueryable&lt;Doctors&gt;();

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 2013-07-26
    • 2021-09-14
    • 2020-04-13
    • 2013-03-21
    • 2021-09-01
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多