我收到此錯誤:UPDATE語句衝突與asp.net的MVC外鍵約束5
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_TitleMember". The conflict occurred in database "ParishDBSQL", table "dbo.Titles", column 'title_id'. The statement has been terminated.
控制器
取得動作
public ActionResult Edit(int? id)
{
var member = (from h in db.Members
join f in db.Titles on h.title_id equals f.title_id
where h.m_id == id
select new
{
title_id = h.title_id,
}).First();
var viewmodel = new MembersViewModel();
viewmodel.title_id = member.title_id;
ViewBag.Titles = new SelectList(db.Titles.ToList(), "title_id", "Titles", viewmodel.title_id);
return View(viewmodel);
}
發帖行動
public ActionResult Edit(MembersViewModel vm)
{
if (ModelState.IsValid)
{
var member = db.Members.Find(vm.m_id);
member.title_id = vm.title_id;
ViewBag.Titles = new SelectList(db.Titles.ToList(), "title_id", "Titles", vm.title_id);
db.Members.Attach(member);
db.Entry(member).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
查看
<div class="col-md-4">
<div class="form-group">
<label>Title</label>
@Html.DropDownList("Titles")
@Html.ValidationMessageFor(model => model.title_id)
</div>
</div>
型號
public partial class Title
{
public Title()
{
this.Heads = new HashSet<Head>();
this.Members = new HashSet<Member>();
}
public int title_id { get; set; }
public string Titles { get; set; }
public virtual ICollection<Head> Heads { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
視圖模型
public class MembersViewModel
{
public int m_id { get; set; }
public string titles { get; set; }
public int title_id { get; set; }
}
我想使用我的成員表格表上的下拉列表來更新title_id,但是我得到上面顯示的錯誤。
member.title_id = vm.title_id但它是在這裏,因爲它給了我0,而不是一個有效的數字和你做的代碼是與我同 – ninjaXnado 2014-12-04 12:59:35
所以解決您的問題:) – faby 2014-12-04 13:00:07
沒有它給了我同樣的錯誤 – ninjaXnado 2014-12-04 13:01:33