使用sql server 2008创建一个表并使用linq to sql。我用的是asp.net mvc3 剃刀观点。
尝试创建新记录时遇到以下异常
违反PRIMARY KEY约束' PK_Department'。无法在对象' dbo.Department'。
中插入重复的密钥我试图将记录插入到一个表中,该表已将其id列作为另一个表中的外键。我无法理解这是什么错误。有人能帮助我吗?
部门控制器中的代码
// GET: /Department/Create
public ActionResult Create()
{
Department department = new Department();
return View(department);
}
//
// POST: /Department/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
Department department = new Department();
try
{
// TODO: Add insert logic here
UpdateModel(department);//Updates all the fields in the table
departmentRepository.Add(department);//Inserts the record
departmentRepository.Save();//Saves all the fields in the record
return RedirectToAction("Index");
}
catch(Exception ex)
{
var Ex_mesg = ex.Message;
return View("Error");
}
}
部门存储库中的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace VisitorManagementSystem.Models
{
public class DepartmentRepository
{
private VisitorManagementDataContext db = new VisitorManagementDataContext();
//QUERYABLE METHODS
public IQueryable<Department> FindAllDepartment()
{
return db.Departments;//returns all the departments in the table
}
//ADD, SAVE, DELETE Methods
public void Add(Department department)
{
db.Departments.InsertOnSubmit(department);//Adds a record to the table
}
public void Save()
{
db.SubmitChanges();//Saves the record to the table
}
public void Delete(Department department)
{
db.Departments.DeleteOnSubmit(department);//Deletes the record on submit.
}
}
}
剃须刀视图中的代码
@model VisitorManagementSystem.Models.Department
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript">
</script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Department</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
答案 0 :(得分:1)
听起来您正在尝试将记录插入到与其他现有记录具有相同密钥的Department表中。在不了解您的架构,现有数据或代码的情况下,我不认为我能提供更好的解释。