我正在尝试在一个简单的模型上进行测试。我无法弄清楚如何将用户附加到正在提交的模型。我尝试了几种不同的方法,但似乎无法提交模型。
public class StockController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public StockController()
{
}
// GET: Stock
[Authorize(Roles = "canEdit")]
public ActionResult Index()
{
var currentUserId = User.Identity.GetUserId();
var userStocks = db.Stocks.Where(p => p.User.Id == currentUserId);
//var test1 = userStocks.ToList();
return View(userStocks.ToList());
}
// GET: Stock/Details/5
[Authorize(Roles = "canEdit")]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Stock stock = db.Stocks.Find(id);
if (stock == null)
{
return HttpNotFound();
}
return View(stock);
}
// GET: Stock/Create
[Authorize(Roles = "canEdit")]
public ActionResult Create()
{
return View();
}
// POST: Stock/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "canEdit")]
public ActionResult Create([Bind(Include = "StockId,Name,Ticker")] Stock stock)
{
//var currentUserId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
//var user = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
// var user = db.Users.Select(p => p.UserName == User.Identity.GetUserName()).FirstOrDefault();
stock.User = user;
db.Stocks.Add(stock);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(stock);
}
这是用户的模型和股票
public class Stock
{
public int StockId { get; set; }
public string Name { get; set; }
public string Ticker { get; set; }
public virtual ApplicationUser User { get; set;}
}
和应用程序用户模型
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Stock> Stocks { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
答案 0 :(得分:4)
用户管理器使用与您的控制器不同的ApplicationDbContext
对象实例。因此,EF无法正确跟踪用户对象。要解决此问题,只需改变您的Stock
类,如下所示:
public class Stock
{
// other members here
public string UserID { get; set; }
public virtual ApplicationUser User { get; set; }
}
现在更改回发创建动作方法,如下所示:
public ActionResult Create([Bind(Include = "StockId,Name,Ticker")] Stock stock)
{
if (ModelState.IsValid)
{
stock.UserID = User.Identity.GetUserId();
db.Stocks.Add(stock);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(stock);
}