我正在嘗試在我的配方表和 AspNet 用戶表之間創建 1 對多的關系,但是每當我創建新配方時,我都會以 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;
}
EDIT 2: Thanks for the help, the code correctly assigned a foreign key now.
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不使用 saveDbContextinstance。在這種情況下,您會發現使用外鍵而不是導航屬性分配用戶更簡單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/337911.html
標籤:c# entity-framework asp.net-mvc-4 model-view-controller foreign-keys
下一篇:用C計算檔案中的字母
