I'm trying to insert an containing object that has a relationship.
User > Company
First of all I need to get the UserID data in the% Create %
public ActionResult Create()
{
var usuarioLogado = User.Identity.Name;
var usuarioDb= new SelectList(db.Users.Where(u => u.Email == usuario), "Id", "Email");
ViewBag.UsuarioId = UsuarioDb;
return View();
}
And my View
receiving:
<div class="form-group formulario">
@Html.LabelFor(model => model.Usuario.Email, htmlAttributes: new { @class = "control-label col-md-2", })
<div class="col-md-10">
@* @Html.EditorFor(model => model.UsuarioId, new { htmlAttributes = new { @class = "form-control", @disabled = "disabled", @Value = ViewBag.UsuarioId } })*@
@Html.DropDownList("UsuarioId", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled" })
@Html.ValidationMessageFor(model => model.UsuarioId, "", new { @class = "text-danger" })
</div>
</div>
However, when sending the data to my View
controller
:
public async Task<ActionResult> Create([Bind(Include = "EmpresaId,UsuarioId,Nome,Cnpj")] Empresa empresa)
{
if (ModelState.IsValid)
{
empresa.EmpresaId = Guid.NewGuid();
db.Empresa.Add(empresa);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.UsuarioId = new SelectList(db.Users, "Id", "Email", empresa.UsuarioId);
return View(empresa);
}
I get the error:
The INSERT statement conflicts with the FOREIGN KEY constraint "FK_dbo.Dbo.AspNetUsers_UsuarioId". The conflict occurred in database "HeritageContext", table "dbo.AspNetUsers", column 'Id'. The statement has been terminated.
What is the correct way to enter the data?