如果我有一个控制器来处理数据库查询,我在添加/删除数据库时没有问题
public class AccountController : Controller
{
protected UserManager<ApplicationUser> UserManager { get; set; }
protected ApplicationDbContext db { get; set; }
public string GetUserId()
{
return User.Identity.GetUserId();
}
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
this.db = new ApplicationDbContext();
}
public AccountController(UserManager<ApplicationUser> userManager)
{
db = new ApplicationDbContext();
UserManager = userManager;
}
[HttpGet]
public ActionResult Manage()
{
// Populate our view
ManageViewModel model = new ManageViewModel();
// Get our user id and then find what cars our user has
string id = GetUserId();
// User Cars
model.UserMajors = (from m in db.UserHasCars where m.ApplicationUserId == id select m.Car).ToList();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(FormCollection form)
{
// snip
var queryCars = (from m in db.UserHasCars where m.ApplicationUserId == id select m).ToList();
foreach (var record in queryCars)
{
db.UserHasCars.Remove(record);
}
db.SaveChanges();
// snip
}
一切顺利,如预期的那样。但是操作方法“管理”更适合另一个控制器而不是帐户。我决定将这两个动作移动到我的设置控制器中,并保持其他所有内容相同 - 相同的构造函数,相同的属性。在我的设置控制器中,当我发布到管理时,它会在db.UserHasCars.Remove(record)
吐出这个可怕的中断:
"A referential integrity constraint violation occurred: A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion."
我想移动更适合其他控制器的操作,但是出现此错误,我可能必须将所有数据库调用保存在单个控制器中。如何将我的动作移动到另一个控制器?