MVC 5 Razor代码优先使用IdentityUser的EF连接表

时间:2014-03-05 06:19:28

标签: asp.net-mvc entity-framework razor

所以我有这两个类,用户来自个人用户帐户

public class User : IdentityUser
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string Email { get; set; }      
    public virtual ICollection<Basket> Baskets { get; set; }     
}

public class Basket
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Key]
    public int BasketId { get; set; }
    public string Name { get; set; }
    public int Words { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

EF已经创建了2个FK的UserBaskets。我在我播种的篮子课程中有项目。

我的问题是,如何在控制器中的联结表中添加行?例如,一个登录用户点击一个篮子并返回Id ...现在我已经

        [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Basket(int? basketid)
    {
        if (ModelState.IsValid)
        {
            var job = User.Identity.GetUserId();
            job.Baskets.Add(basketid);
            db.Users.Add(job);
            db.SaveChanges();
            return RedirectToAction("Basket");
        }

        return View(db.Baskets.ToList());
    }

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我最终选择手动添加联结表

public class UserBasket
{
    [Key]
    public int UserBasketId { get; set; }

    public virtual User User { get; set; }

    public virtual Basket Basket { get; set; }

    public DateTime Date { get; set; }
}

并且可以像这样使用identityUser添加一行

UserManager<User> userManager = new UserManager<User>(new UserStore<User>(db));
var user = userManager.FindById(User.Identity.GetUserId());
Basket basket = db.Basket.Find(id);
var userbasket = new UserBasket {User = user, Basket = basket, Date = DateTime.Now };
db.UserBasket.Add(userbasket);
db.SaveChanges();