我正在嘗試在我的配方表和 AspNet 用戶表之間創建一對多的關系,但是每當我創建一個新配方時,我最終都會以 NULL 作為我的外鍵。
public virtual ApplicationUser ApplicationUser { get; set; }在我的Recipe 模型中并且
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);
}
uj5u.com熱心網友回復:
有很多方法可以做到這一點,我個人在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不使用保存DbContext實體。在這種情況下,您會發現使用外鍵分配用戶更簡單,而不是導航屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420643.html
標籤:
上一篇:根據資料值啟用/禁用按鈕
