繁体   English   中英

外键在 ASP.NET 中是 NULL 的一对多关系。 如何将其添加到控制器中?

[英]Foreign key is NULL in ASP.NET in 1 to many relationship. How do I add it in controller?

我正在尝试在我的配方表和 AspNet 用户表之间创建 1 对多的关系,但是每当我创建新配方时,我都会以 NULL 作为外键。 public virtual ApplicationUser ApplicationUser { get; set; } public virtual ApplicationUser ApplicationUser { get; set; }在我的Recipe 模型public List<Recipe> Recipes { get; set; } public List<Recipe> Recipes { get; set; } public List<Recipe> Recipes { get; set; }在我ApplicationUser模型

我在DbInitializer 中添加了一些测试配方后的配方表 第 3 行是通过 localhost 创建的,外键为 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();

我只是不知道如何在创建新配方时在控制器中设置外键:

        [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);
    }

对不起,如果我的帖子乱七八糟,这是我第一次在这里发帖。

编辑:我不确定,但这是你要求的吗? 我只需输入 user.Id 就可以访问用户 ID,对吗?

   public class RecipesController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly UserManager<ApplicationUser> _userManager;

    public RecipesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

编辑 2:感谢您的帮助,代码现在正确分配了一个外键。

        public async Task<IActionResult> Create([Bind("Id,Title,Introduction,Ingredients,Instructions,Nutrients")] Recipe recipe)
    {
        if (ModelState.IsValid)
        {
            // Adding the foreign key to recipes
            var user = await _userManager.GetUserAsync(User);
            recipe.UserId = user.Id;
            
            _context.Add(recipe);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(recipe);
    }

有很多方法可以做到这一点,我个人在DbContext.SaveChanges()方法中分配审计信息,但这是一种全局方法,超出了本文的范围。

在基本层面上,您需要在调用SaveChanges()之前分配用户,因此以下代码可能适用于您的情况:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Title,Introduction,Ingredients,Instructions,Nutrients")] Recipe recipe)
{
    if (ModelState.IsValid)
    {
        // assign the user
        var user = await _userManager.GetUserAsync(User);
        recipe.ApplicationUser = user;

        _context.Add(recipe);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(recipe);
}

注意:这只是一个指南,在某些情况下,上述分配可能不起作用,特别是如果您的UserManager不使用 save DbContext实例 在这种情况下,您会发现使用外键而不是导航属性分配用户更简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM