Error creating data with foreign key

Asked

Viewed 419 times

3

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

Model

2 tables, Departamento and Funcionario, the official has the foreign key IdDepartamento.

And I ran the controllers all neat, I can add a department without problems, but when I add an employee, he error, screen of registering run with the dropdown of the departments:

inserir a descrição da imagem aqui

ae when I put a name and id of the department already created, gives the following error:

inserir a descrição da imagem aqui

the controller employee:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([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 the ViewBag:

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

View Create of the Staff: @model MVC4.Models.Functional

@{
    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

Guys, thanks to everyone who helped me, I was able to solve it using the following code on FuncionariosController:

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

That is, he gives a find in departments to see if it meets the past Iddepartment, if it is == null, dp gets the Department class.

  • The error described has nothing to do with error in the foreign key, it is just the opposite, the foreign key is generating the error why it is working, and warning that the department table has nothing. idDepartment = 1, does not exist.

  • We also need your code View.

  • @Ciganomorrisonmendez I will post the View do create

  • @Ciganomorrisonmendez has table data Departments

  • I agree with @Christianberegula, this error occurs because your employee table is referencing to a table that does not give you the expected record. Very common error... Can be simulated in SQL. The idea is that this field "Iddepartamento", is a combobox with the list of departments (Register the departments before the employee), which will work well.

  • @Ciganomorrisonmendez I made some changes to the question, please take a look

Show 1 more comment

2 answers

4


It’s not good here:

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

Being a foreign key, you can fill it out using a resource on Controller. 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;
  • I made a few changes to the question, please take a look

  • when I put your code in the view, it error in the " (Ienumerable<Department>) "The type or namespace 'Department' could not be found"

  • Placed at the beginning of View @using MeuProjeto.Models?

  • I put so in my Create do Funcionario: "Meuprojeto.Models.Funcionario "

  • So how? I can’t read your screen. Update your question with the full try so I can help you.

  • ta, I’ll put my full Create view of the employees, just a min

  • Updated @Ciganomorrisonmendez

  • 1

    @Furlan You’re not even following what I put in my answer. I don’t know if it’s worth continuing with this.

Show 4 more comments

0

This error occurs due to the non-existence of records in the Departments table. Perform a load of data in this table and change the Iddepartment field to a combobox (Dropdownlist). Follow model:

HTML

@Html.DropDownListFor(m => m.IdDepartamento, 
            new SelectList(Model.Departamento, "--Escolha o departamento--" )
  • I made a few changes to the question, please take a look

Browser other questions tagged

You are not signed in. Login or sign up in order to post.