ASP.NET一对多关系中外键为NULL,如何在控制器中设置外键?
问题:Recipe表与AspNetUser表建立一对多关系后创建Recipe时外键为NULL
问题背景
尝试在Recipe表和AspNetUser表之间建立一对多关系,但是每次创建新Recipe时外键都为NULL,已完成的模型配置如下:
- Recipe模型 中添加代码:
public virtual ApplicationUser ApplicationUser { get; set; } - ApplicationUser模型 中添加代码:
public List<Recipe> Recipes { get; set; }
在DbInitializer中添加测试数据的代码如下,测试数据的外键可正常赋值,但手动通过本地站点创建的Recipe外键为NULL:
foreach (var u in db.Users.Include(b => b.Recipes) ) { for (int i = 1; i < 3; i++) { u.Recipes.Add(new Recipe { Title = $"{i}", Introduction = $"{i}", Ingredients = $"{i}", Instructions = $"{i}", Nutrients = $"{i}" }); } } db.SaveChanges();
初始控制器代码
最初的Create接口未处理外键赋值,代码如下:
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Title,Introduction,Ingredients,Instructions,Nutrients")] Recipe recipe) { if (ModelState.IsValid) { _context.Add(recipe); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(recipe); }
控制器依赖注入配置
已在控制器中注入UserManager<ApplicationUser>用于获取当前登录用户,控制器构造函数代码如下:
public class RecipesController : Controller { private readonly ApplicationDbContext _context; private readonly UserManager<ApplicationUser> _userManager; public RecipesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager) { _context = context; _userManager = userManager; }
最终解决方案
在保存Recipe前先获取当前登录用户,手动给外键字段赋值即可,修改后的Create方法代码如下:
public async Task<IActionResult> Create([Bind("Id,Title,Introduction,Ingredients,Instructions,Nutrients")] Recipe recipe) { if (ModelState.IsValid) { // 为Recipe赋值用户外键 var user = await _userManager.GetUserAsync(User); recipe.UserId = user.Id; _context.Add(recipe); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(recipe); }
内容的提问来源于stack exchange,提问作者tryingmybest64
相关产品推荐
相关产品推荐

