Insert data with related objects

1

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?

    
asked by anonymous 10.01.2017 / 22:25

1 answer

2

By default, elements marked with disabled will not send pro server-side values.

Your error says

  

That is, it did not find the primary key of the value used in empresa.UsuarioId .

To solve, you can change disabled to readonly .

@Html.DropDownList("UsuarioId", null, htmlAttributes: new { @class = "form-control", @readonly = "readonly" })
    
10.01.2017 / 22:43