简体   繁体   English

ASP.NET MVC 5 ApplicationUser作为外键

[英]ASP.NET MVC 5 ApplicationUser as foreign key

What I would like to be able to do is update the UserContent table any time a user visits a content page. 我希望能够做的是在用户访问内容页面时更新UserContent表。 I created a controller to try and manually input data before implementing this but I am getting a foreign key error: 我创建了一个控制器来尝试在实现之前手动输入数据,但是我收到了一个外键错误:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.UserContent_dbo.IdentityUser_ApplicationUserId". The conflict occurred in database "COMPILING_a6a38dac907c4816af896bbeb6cdaa55", table "dbo.IdentityUser", column 'Id'.
The statement has been terminated.

Model: 模型:

public class UserContent
{
    public int ID { get; set; }

    [Display(Name = "Times Visited")]
    public int Visited { get; set; }

    [Display(Name = "Rating")]
    public byte Rating { get; set; }

    [Display(Name = "Content Page")]
    public int ContentID { get; set; }

    [Display(Name = "User")]
    public string ApplicationUserId { get; set; }

    public virtual Content Content { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

Controller: 控制器:

private CompilingContext db = new CompilingContext();
private ApplicationDbContext db2 = new ApplicationDbContext();  

public ActionResult Create([Bind(Include="ID,Visited,Rating,ContentID,ApplicationUserId")] UserContent usercontent)
    {
        if (ModelState.IsValid)
        {
            db.UserContent.Add(usercontent);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.ApplicationUserId = new SelectList(db2.Users, "Id", "UserName", usercontent.ApplicationUserId);
        ViewBag.ContentID = new SelectList(db.Contents, "ID", "Title", usercontent.ContentID);
        return View(usercontent);
    }

I was able to solve this issue by putting all of my models into one context. 通过将所有模型放在一个上下文中,我能够解决这个问题。 I originally had them in two separate contexts which was causing issues as it was giving me two separate databaes. 我最初在两个不同的环境中使用它们,这引起了问题,因为它给了我两个独立的数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM