代码第一种方法与mvc3

时间:2013-06-13 16:26:42

标签: asp.net asp.net-mvc-3 ef-code-first

我想知道我是否做得很好。我有两种模式:

人员:

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>
}

1 个答案:

答案 0 :(得分: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();

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