2011-02-02 99 views
0

正在使用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. 
     } 


    } 
} 

在Razor視圖

@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

錯誤信息不能更清楚。 – 2011-02-02 14:56:32

回答

1

的代碼聽起來像你試圖插入一條記錄部門表與另一個現有記錄具有相同的關鍵字。不知道更多關於您的模式,現有數據或您的代碼,儘管我認爲我不能提供比這更好的解釋。

+0

我已更新代碼... – Vasanth 2011-02-02 15:02:56