我希望能够在用户访问内容页面时更新UserContent表。我创建了一个控制器来尝试在实现之前手动输入数据,但是我收到了一个外键错误:
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.
型号:
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; }
}
控制器:
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);
}
答案 0 :(得分:2)
我能够通过将所有模型放在一个上下文中来解决这个问题。我最初在两个不同的环境中使用它们,这导致了问题,因为它给了我两个独立的数据库。