我有一个问题,将一条记录插入实体 ProfessionalEmploymentRecord EF 最终会分别在每个实体中复制现有的 Professional、Program、Role 记录。我试图用我的数据库中的现有键/值对显式地初始化专业、程序、角色,但 EF 仍然使用新键创建重复值。
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; }
}
当使用下面的创建时,我最终会在三个相关实体中得到新记录,尽管它们存在并且有一个键集。换句话说,我最终在三个相关实体中得到了具有新主键(加一)的值副本。
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 会在 reco 中设置 *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();
}
}