[英]How should I add a database record with user field set to currently logged user ASP.NET MVC
將類別添加到登錄用戶時出現問題。 我遇到錯誤System.InvalidOperationException: "Sequence has no elements."
。
我的代碼:
public class AppUser
{
public int Id { get; set; }
public string Nickname { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime BirthDate { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public AppUser AppUser { get; set; }
public int AppUserId { get; set; }
}
public class CategoryAndAppUserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int AppUserId { get; set; }
}
// GET: Categories/Create
public ActionResult Create()
{
return View();
}
我的控制器:
// GET: Categories/Create
public ActionResult Create()
{
return View();
}
// POST: Categories/Create
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CategoryAndAppUserViewModel category)
{
if (ModelState.IsValid)
{
string userId = User.Identity.GetUserId();
AppUser appUser = _context.AppUsers.Single(u => u.Name == userId);
var categoryVM = new Category { Name = category.Name, AppUser = appUser };
appUser.Categories.Add(categoryVM);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
我想做的是:當用戶登錄后,轉到“ My Examples
,創建新的Category
,填寫新的類別名稱,應用程序必須自動將新類別添加到已登錄的用戶。 主要問題是獲取登錄的用戶ID。
將類別添加到登錄用戶時出現問題。 我遇到錯誤System.InvalidOperationException: "Sequence has no elements."
。
我的代碼:
public class AppUser
{
public int Id { get; set; }
public string Nickname { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime BirthDate { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public AppUser AppUser { get; set; }
public int AppUserId { get; set; }
}
public class CategoryAndAppUserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int AppUserId { get; set; }
}
// GET: Categories/Create
public ActionResult Create()
{
return View();
}
我的控制器:
// GET: Categories/Create
public ActionResult Create()
{
return View();
}
// POST: Categories/Create
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CategoryAndAppUserViewModel category)
{
if (ModelState.IsValid)
{
string userId = User.Identity.GetUserId();
AppUser appUser = _context.AppUsers.Single(u => u.Name == userId);
var categoryVM = new Category { Name = category.Name, AppUser = appUser };
appUser.Categories.Add(categoryVM);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
我想做的是:當用戶登錄后,轉到“ My Examples
,創建新的Category
,填寫新的類別名稱,應用程序必須自動將新類別添加到已登錄的用戶。 主要問題是獲取登錄的用戶ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.