2015-10-13 76 views
0

我正在尝试在简单模型上创建一个测试。我无法弄清楚如何将用户附加到正在提交的模型上。我尝试了几种不同的方法,但似乎无法让模型提交。C#Asp .net Identity将当前用户添加到模型

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

} 

回答

2

用户管理器使用不同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); 
}