0

我想知道我是否以正确的方式做事。我有两个模型:

人员 :

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>&nbsp;</span>
        <input type="submit" value="Envoyer" class="submit" />
    </p>

</div>
}
4

1 回答 1

1

您可以在执行 SaveChanges() 之前将 Employee 实例附加到上下文。

像这样的东西应该有效;

RH_Personnel employee = (RH_Personnel)HttpContext.Session["Employe"];
db.RH_Personnel.Attach(employee);
rh_attestation.Employee = employee;
db.RH_Attestation.Add(rh_attestation);
db.SaveChanges();

我没有测试它,所以告诉我我们是否朝着正确的方向前进;)

于 2013-06-13T18:31:44.277 回答