我有一個問題,即向實體ProfessionalEmploymentRecord EF插入一條記錄,最終分別在每個實體中複製現有的Professional,Program,Role記錄。我曾嘗試在數據庫中明確初始化Professional,Program,Role和現有的鍵/值對,但EF仍然使用新鍵創建重複值。DbContext.SaveChanges
public class ProfessionalEmploymentRecord
{
public int ProfessionalEmploymentRecordId {get; set; }
public virtual Professional Professional { get; set; }
public virtual Program Program { get; set; }
public virtual Role Role { get; set; }
}
public class Program
{
public int ProgramId { get; set; }
[MaxLength(20)]
public string Name { get; set; }
}
public class Role
{
public int RoleId { get; set; }
[MaxLength(50)]
public string Name { get; set; }
}
public class Professional
{
public int ProfessionalId { get; set; }
[MaxLength(20)]
public string Name { get; set; }
}
當使用下面的Create時,我最終得到三個相關實體中的新記錄,雖然它們存在並有一個鍵集。換句話說,我最終得到三個相關實體中具有新主鍵的值副本(增加1)。
public ActionResult Create(ProfessionalEmploymentRecord professionalemploymentrecord)
{
if (ModelState.IsValid)
{
db.ProfessionalEmploymentRecords.Add(professionalemploymentrecord);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(professionalemploymentrecord);
}
按照要求
我已經使用以下代碼來測試@model My.Models.ProfessionalEmploymentRecord
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend> Professional Employment Record</legend>
<div class="editor-label">
Professional
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Professional.Name)
@Html.ValidationMessageFor(model => model.Professional.Name)
</div>
<div class="editor-label">
Program
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Program.Name)
@Html.ValidationMessageFor(model => model.Program.Name)
</div>
<div class="editor-label">
Role
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Role.Name)
@Html.ValidationMessageFor(model => model.Role.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
。 (我看到執行SaveChanges設置* Id ++在記錄)。
public void TestDummyAdd()
{
Professional prof = new Professional { ProfessionalId = 1, Name = "Chris" };
Program prog = new Program { ProgramId = 1, Name = "A" };
Role role = new Role { RoleId = 1, Name = "B" };
ProfessionalEmploymentRecord reco = new ProfessionalEmploymentRecord { Professional = prof, Role = role, Program = prog, ProfessionalEmploymentRecordId = 0 };
if (ModelState.IsValid)
{
db.ProfessionalEmploymentRecords.Add(reco);
db.SaveChanges();
}
}
郵政爲Create()方法調用代碼。你如何初始化或設置它的專業,程序和角色,發佈代碼 – Apurav 2012-08-08 14:35:33