在EF ASP.NET Core 2.1中更新与用户相关的数据将返回null异常

时间:2019-06-21 20:31:26

标签: asp.net-mvc asp.net-core

无法访问ApplicationUser属性BizName,因为在尝试更新编辑后方法时ApplicationUser始终为null。空异常是@行ApplcationUser.BusinessName;

我尝试了

var userFromDb = _db.ApplicationUser.Include(u => u.Customer).Where(u => u.Id == id).FirstOrDefault();

var userFromDb = _db.Customer.Include(u => u.ApplicationUser).Where(u => u.CustomerUserId == id).FirstOrDefault();

控制器

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditUser(string id, ApplicationUser applicationUser)
{
        if (id != applicationUser.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            var userFromDb = _db.ApplicationUser.Include(u => u.Customer).Where(u => u.Id == id).FirstOrDefault();
            ....
            _db.SaveChanges();
            return RedirectToAction(nameof(Index));
        }

        return View(applicationUser);
}

型号

public class Customer
{
    [Key, ForeignKey("ApplicationUser")]
    public string CustomerUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    public string BizName
    {
        get
        {
            return ApplicationUser.BusinessName;
        }
    }
}

0 个答案:

没有答案