Hello, I am not able to insert data into a table that has foreign key, follow my model:
2tables,Departamento
andFuncionario
,theemployeehastheforeignkeyIdDepartamento
.
AndImanagedthecontrollers
everythingright,Icanaddadepartmentwithoutproblems,butwhenIaddanemployee,iterror,screenofficialemployeewithdropdown
ofdepartments:
WhenIputanameandthedepartmentidalreadycreated,itgivesthefollowingerror:
ocontroller
oftheofficial:
[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.