gpt4 book ai didi

c# - ASP.NET MVC 5 ApplicationUser 作为外键

转载 作者:行者123 更新时间:2023-11-30 17:00:29 25 4
gpt4 key购买 nike

我希望能够在用户访问内容页面时更新 UserContent 表。我创建了一个 Controller 来尝试在实现之前手动输入数据,但我收到外键错误:

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

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

最佳答案

我能够通过将所有模型置于一个上下文中来解决这个问题。我最初将它们放在两个单独的上下文中,这导致了问题,因为它给了我两个单独的数据库。

关于c# - ASP.NET MVC 5 ApplicationUser 作为外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com