【问题标题】:NullReferenceException when trying to set value to an object尝试为对象设置值时出现 NullReferenceException
【发布时间】:2021-08-25 08:10:25
【问题描述】:

我正在尝试将当前的 userId 添加到我的对象中,但我得到一个 nullreferenceexception。 我正在使用带有(身份验证)的 c# .net 核心 MVC 项目。

我认为当我想创建一个新的设备对象时,userId 尚未启动,但我该如何解决?

控制器:

// POST: Device/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Device device)
    {
        if (ModelState.IsValid)
        {
            //get current userId
            string userId = _userManager.GetUserId(HttpContext.User);
            
            //create a device
            int id = _deviceService.Create(device);

            //set userId to the device
            Device deviceToLinkToUser = _deviceService.FindById(id);
            deviceToLinkToUser.User.Id = userId;

            return RedirectToAction(nameof(Details), new { id = id });
        }
        return View(device);
    }

服务:

public int Create(Device device)
    {
            _context.Devices.Add(device);
            _context.SaveChanges();

            return device.Id;
    }

数据类:

public class Device
{
    public int Id { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }

    public Damage Damage { get; set; }
    [Display(Name = "Damage")]
    public int DamageId { get; set; }

    public CustomUser User { get; set; }
}

查看:

@model RepairAtDems.Data.Device


@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>
<h4>Device</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Brand" class="control-label"></label>
                <input asp-for="Brand" class="form-control" />
                <span asp-validation-for="Brand" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Model" class="control-label"></label>
                <input asp-for="Model" class="form-control" />
                <span asp-validation-for="Model" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DamageId" class="control-label"></label>
                <select asp-for="DamageId" class="form-control" asp-items="ViewBag.DamageId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

我错过了什么吗?

【问题讨论】:

    标签: entity-framework-core asp.net-core-mvc asp.net-identity


    【解决方案1】:

    您的线路:

    Device deviceToLinkToUser = _deviceService.FindById(id);
    

    正在检索设备,但可能不是“包含”...用户,所以当您到达线路时:

    deviceToLinkToUser.User.Id = userId;
    // deviceToLinkToUser.User == null !!!!!!
    

    因此,当您尝试将 UserId 分配给属性“Id”时,找不到拥有对象“User”。因此你的错误。

    如果您想在获取设备时从数据库中检索用户,那么您需要在 Service.FindById() 方法中实现它。

    public Device FindById(int id)
    {
        return _Context.Devices.
            .Include(d => d.User)
            .SingleOrDefault(d => d.Id == id)
    }
    

    如果您不想检索用户而只是在设备上设置用户,那么您需要使用:

    deviceToLinkToUser.User = new CustomUser { Id = userId };
    

    【讨论】:

      猜你喜欢
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多