Error creating data with foreign key

3

Hello, I am not able to insert data into a table that has foreign key, follow my model:

2tables,DepartamentoandFuncionario,theemployeehastheforeignkeyIdDepartamento.

AndImanagedthecontrollerseverythingright,Icanaddadepartmentwithoutproblems,butwhenIaddanemployee,iterror,screenofficialemployeewithdropdownofdepartments:

WhenIputanameandthedepartmentidalreadycreated,itgivesthefollowingerror:

ocontrolleroftheofficial:

[HttpPost][ValidateAntiForgeryToken]publicActionResultCreate([Bind(Include="IdFuncionario,Nome,IdDepartamento")] Funcionario funcionario)
    {
        if (ModelState.IsValid)
        {
            db.Funcionarios.Add(funcionario);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(funcionario);
    }

Funcionarios Create Controller to generate ViewBag :

    // GET: Funcionarios/Create
    public ActionResult Create()
    {
        ViewBag.IdDepartamento = new SelectList(db.Departamentos, "IdDepartamento", "Nome");
        return View();
    }

View Create Employee:     @model MVC4.Models.Funtionary

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 

{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Funcionario</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.IdDepartamento, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.ValidationMessageFor(model => model.IdDepartamento, "", new { @class = "text-danger" })
            @Html.DropDownList("IdDepartamento", ViewBag.IdDepartamento as SelectList, new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Thank you

RESOLVED

Personal, thanks to all who helped me, I was able to solve using the following code in FuncionariosController :

             var dp = db.Departamentos.Find(Convert.ToInt32(funcionario.IdDepartamento));
            if (dp == null)
            {
                dp = new Departamento();
            }
            funcionario.Departamento = dp;

That is, it gives a find in departments to see if it finds the lastDepartment id, if it is == null, dp receives the Department class.

    
asked by anonymous 18.11.2015 / 19:40

2 answers

4

This is not good here:

@Html.EditorFor(model => model.IdDepartamento, new { htmlAttributes = new { @class = "form-control" } })

Being a foreign key, you can populate it using a Controller resource. My suggestion is:

@Html.DropDownListFor(model => model.IdDepartamento, ((IEnumerable<Departamento>)ViewBag.Departamentos).Select(option => new SelectListItem
{
    Text = option.Nome,
    Value = option.IdDepartamento.ToString(),
    Selected = (Model != null) && (Model.IdDepartamento== option.IdDepartamento)
}), "Selecione...", new { @class = "form-control" })

This ViewBag.Departamentos you can fill in Action GET of Create as follows:

ViewBag.Departamentos = db.Departamentos;
    
18.11.2015 / 20:14
0

This error occurs because there are no records in the department table. Perform a load of data on this table and change the FieldIndex field to a combobox (Dropdownlist). Follow template:

HTML

@Html.DropDownListFor(m => m.IdDepartamento, 
            new SelectList(Model.Departamento, "--Escolha o departamento--" )
    
18.11.2015 / 21:12