Создаю таблицу с SQL Server 2008 и использую LINQ для SQL.Я использую asp.net mvc3 с видом бритвы.
при попытке создать новую запись получаю следующее исключение
Нарушение ограничения PRIMARY KEY 'PK_Department'.Невозможно вставить повторяющийся ключ в объект 'dbo.Department'.
Я пытаюсь вставить запись в таблицу, в которой есть столбцы идентификаторов в качестве внешнего ключа в другой таблице.Я не могу понять, что это за ошибка.Может ли кто-нибудь мне помочь?
Код в контроллере отдела
// 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>