ASP.NET 2.2 Core向模型添加用户会引发nullreference异常

时间:2019-06-13 14:48:33

标签: c# asp.net entity-framework asp.net-core

我有一个模型,该模型具有类型为ApplicationUser的属性Publisher。当我尝试创建模型时,它给了我一个nullreference异常。

在模型中:

[Display(Name = "Publisher")]
[ForeignKey("PublisherId")]
public ApplicationUser Publisher { get; set; }

在ApplicationUser中:

public ICollection<Model> PublishedModels { get; set; }

数据库上下文中的多对一关系:

b.HasMany(u => u.PublishedModels)
     .WithOne(v => v.Publisher)
     .IsRequired()
     .OnDelete(DeleteBehavior.Restrict);

在控制器的Create方法中(获取当前用户):

var user = await _userManager.GetUserAsync(HttpContext.User);

我在这行上得到一个空引用:

model.Publisher = user;

我很困惑,我确认用户不为null。 Model不为null,并且ModelState有效。那我为什么不能将该值分配给model.Publisher?奇怪的是,如果我不修改模型,而只是将其保存到数据库中,它将起作用。但是我也需要添加发布者。如果只设置日期,也可以。

这有效,但是在删除注释时,它会在设置日期时抱怨为空引用。

public async Task<IActionResult> Create([Bind(include:"...")] Model model)
{
    ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User);
    try
    {
        if (ModelState.IsValid)
        {
            model.PublicationDate = DateTime.Now;

            //user.PublishedModels.Add(model);

            _context.Add(model);
            //_context.Update(model.Publisher);

            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }
    }
    catch (DataException /*dex*/)
    {
        ModelState.AddModelError("", "...");
    }
    return View(model);
}

在下面的堆栈跟踪中,它在方法的第一行崩溃...

NullReferenceException: Object reference not set to an instance of an object.
WebApp.Controllers.Admin.ModelController.Create(Model model) in 
ModelController.cs
-
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind(include:"...")] Model model)
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    user.PublishedModels.Add(model);
    model.PublicationDate = DateTime.Now;
    model.Publisher = user;
    try
    { 
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)

System.Threading.Tasks.ValueTask.get_Result() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext上下文) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(下一个参考状态,参考作用域范围,参考对象状态,参考布尔已完成) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext上下文) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(下一个参考状态,参考作用域范围,参考对象状态,参考布尔已完成) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)

1 个答案:

答案 0 :(得分:1)

无法重现您的问题,请检查您的代码与以下代码之间的区别:

  1. 您在PublishedModels中定义了ApplicationUser,但您引用了PublishedModel
  2. DbContext,对于以下代码,如果在创建Publisher时未设置PublisherIdModel的值,则操作会出错未设置PublisherId的值,但您没有设置,请检查模型和数据库是否相同。

            builder.Entity<ApplicationUser>()
                    .HasMany(u => u.PublishedModels)
                    .WithOne(vv => vv.Publisher)
                    .IsRequired()
                    .OnDelete(DeleteBehavior.Restrict);
    
  3. 使用applicationuser创建模型的方法

            public async Task<IActionResult> Create([Bind("Id,Name")] Model model)
            {
                    ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User);
                    if (ModelState.IsValid)
                    {
                            model.Publisher = user;
                            _context.Add(model);
                            await _context.SaveChangesAsync();
                            return RedirectToAction(nameof(Index));
                    }
                    return View(model);
            }