【发布时间】:2013-06-13 16:26:41
【问题描述】:
我想知道我是否以正确的方式做事。我有两个模型:
人员:
public class RH_Personnel
{
public int RH_PersonnelID { get; set; }
public string Nom { get; set; }
public string Prenom { get; set; }
}
证明:
public class RH_Attestation
{
public int RH_AttestationID { get; set; }
public virtual RH_Personnel Employe { get; set; }
public string TypeAttestation { get; set; }
}
我使用迁移来生成我的表。我知道我做错了什么,因为当我向数据库添加一个新的Attestation 时,它会创建一个新的RH_Personnel,即使它已经存在。
我的控制器:
public ActionResult Create()
{
ViewBag.TypeAttestation = new SelectList(db.RH_TypeAttestation.ToList(),"Type","Type");
RH_Attestation Attestation = new RH_Attestation();
Attestation.Employe = (RH_Personnel)HttpContext.Session["Employe"];
return View();
}
//
// POST: /Attestation/Create
[HttpPost]
public ActionResult Create(RH_Attestation rh_attestation)
{
if (ModelState.IsValid)
{
//rh_attestation.Employe = (RH_Personnel)HttpContext.Session["Employe"];
//rh_attestation.DateDemande = DateTime.Now;
//rh_attestation.DateValidation = rh_attestation.DateDemande;
//rh_attestation.Etat = ATTESTATION_ETAT_ENCOURS;
db.RH_Attestation.Add(rh_attestation);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(rh_attestation);
}
我的看法:
@model Intra.Models.RH_Attestation
@using (Html.BeginForm("Create", "Attestation", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<div class="form_settings">
@Html.HiddenFor(model => model.Employe.Username)
@Html.HiddenFor(Model => Model.Employe.RH_PersonnelID)
<p>
<span>
@Html.Label("Nom") :
</span>
@Html.EditorFor(model => model.Employe.Nom)
</p>
<p>
<span>
@Html.Label("Prénom") :
</span>
@Html.EditorFor(model => model.Employe.Prenom)
</p>
@Html.DropDownList("TypeAttestation", "Selectionner un type")
<p style="padding-top: 15px;">
<span> </span>
<input type="submit" value="Envoyer" class="submit" />
</p>
</div>
}
【问题讨论】:
-
发生的事情是您正在创建一个新的
RH_Attestation并将其Employe属性设置为等于一个新的Employe。您要做的是检查Employe是否存在,如果存在,则调用.Attach(employe)。RH_Personnel和RH_Attestation之间的关系是什么? -
关系是:单个
RH_Attestation绑定到单个RH_Personnel一对一 -
所以这正是发生的事情,您首先创建一个
RH_Personnel,然后创建一个新的RH_Attestation,并将其Employe属性设置为一个新的RH_Personnel。根据您的应用程序的工作流程和RH_Personnel的创建方法,有不同的方法可以解决此问题。您可以发布用于创建新RH_Personnel的代码吗? -
.Attach(employe)是解决方案,谢谢。
标签: asp.net asp.net-mvc-3 ef-code-first