【问题标题】:Issue with DB Entities keeps getting error message System.NullReferenceException数据库实体问题不断收到错误消息 System.NullReferenceException
【发布时间】:2016-06-04 06:01:32
【问题描述】:

我在从 db 获取数据时遇到问题,当我在文本框中键入 id 时,我收到一条弹出消息 System.NullReferenceException。我正在尝试使用记录中的详细信息自动填充文本框。

UserRepository.cs

using System.Collections.Generic;
using System.Linq;
using SampleMvc.Domain;

namespace SampleMvc.Repository
{
    public class UserRepository : IUserRepository
    {
        #region IUserRepository Members

        private UsersDBEntities UsersDBEntities;

        public User GetUser(string lanId)
        {
            return UsersDBEntities.Users.Where(user => user.LanId == lanId).FirstOrDefault();
        }


        #endregion
    }
}

IUserRepository.cs

using SampleMvc.Domain;

namespace SampleMvc.Repository
{
    public interface IUserRepository
    {
        User GetUser(string LanId);
    }
}

UserDetails.cshtml

@model  SampleMvc.Models.UserModel
@{
    ViewBag.Title = "UserDetails";
}

<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>

<script type="text/javascript">

    $(document).ready(function () {
        $('#LanId').change(function () {
            populateUserDetails();
        });

    });

    function populateUserDetails() {
        var user = {};
        user.LanId = $("#LanId").val();
        $.getJSON("PopulateDetails", user, updateFields);
        //$.post("PopulateDetails", user, updateFields, 'json');
    };

    updateFields = function (data) {
        $("#LastName").val(data.lastName);
        $("#FirstName").val(data.FirstName);
        $("#Message").html(data.Message);
    };
</script>



@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal container">


        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.LanId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LanId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LanId, "", new { @class = "text-danger" })
                <br />
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10 ">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.lastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.lastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.lastName, "", new { @class = "text-danger" })
            </div>
        </div>




        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </div>
    </div>

}

用户控制器.cs

using System;
using System.Web.Mvc;
using SampleMvc.Domain;
using SampleMvc.Models;
using SampleMvc.Repository;

namespace SampleMvc.Controllers
{
    public class UserController : Controller
    {
        private readonly IUserRepository _userRepository;

        public UserController()
        {
            _userRepository = new UserRepository();
        }

        public UserController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        public ActionResult UserDetails()
        {
            UserModel model = new UserModel();
            return View(model);
        }

        public JsonResult PopulateDetails(UserModel model)
        {
            UserResultModel userResultModel = new UserResultModel();
            if (String.IsNullOrEmpty(model.LanId))
            {
                userResultModel.Message = "LanId can not be blank";
                return Json(userResultModel,JsonRequestBehavior.AllowGet);
            }

            User user = _userRepository.GetUser(model.LanId);

            if (user == null)
            {
                userResultModel.Message = String.Format("No LanId found for {0}", model.LanId);
                return Json(userResultModel,JsonRequestBehavior.AllowGet);
            }
            userResultModel.lastName = user.lastName;
            userResultModel.FirstName = user.FirstName;

            userResultModel.Message = String.Empty; //success message is empty in this case

            return Json(userResultModel, JsonRequestBehavior.AllowGet);
        }
    }

    public class UserResultModel
    {
        public string lastName { get; set; }
        public string FirstName { get; set; }
        public string Message { get; set; }
    }
}

【问题讨论】:

  • 您实际上并未将 UserDBEntities 设置为任何内容,您只需将其声明为私有。
  • 我很困惑如何修复代码。我需要更改我的退货吗?
  • 我不建议您使用默认构造函数来设置默认存储库。在这种情况下,您会在 DI 中失去意义并可能出现意外行为
  • 我已将其放入模型和控制器中,但不确定我是否正确,但它正在工作,我摆脱了域和存储库文件夹。如果我将代码发布到某个地方,也许您可​​以帮我看一下。看看我做得对不对。

标签: sql-server asp.net-mvc asp.net-mvc-4


【解决方案1】:

在您的存储库类中:

private UsersDBEntities UsersDBEntities;

public UserRepository()
{
   if (UserDBEntities == null)
   {
   UserDBEntities = new UserDBEntities();
   }
}

虽然我建议使用与类名不同的变量名。

这是我的代码示例:

   private SurveyContext db = null;

    public Survey()
    {
        if (db == null)
        {
            db = new SurveyContext();
        }
    }

【讨论】:

  • 那么我在退货中放什么
猜你喜欢
  • 1970-01-01
  • 2022-06-15
  • 2014-04-12
  • 1970-01-01
  • 2021-11-08
  • 2019-08-20
  • 2014-11-21
  • 1970-01-01
  • 2022-11-28
相关资源
最近更新 更多