Insert data with related objects

Asked

Viewed 56 times

1

I’m trying to insert an object containing a relationship.

User > Enterprise

First I need to get the data from User in View of Create I’m doing it this way:

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 who receives:

 <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 controller Post:

 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);
    }

get the bug:

The INSERT statement conflicted with the FOREIGN KEY Constraint "Fk_dbo.Empresas_dbo.Aspnetusers_usuarioid". The Conflict occurred in database "Patrimoniocontexto", table "dbo.Aspnetusers", column 'Id'. The statement has been terminated.

What is the correct way to enter the data ?

  • 1

    Remove the disabled from DropDownList().

1 answer

2


By default, items marked with disabled will not send values to the server-side.

Your mistake says

The INSERT statement conflicted with the FOREIGN KEY Constraint "[...]Usuarioid"

I mean, he didn’t find the Primary key of the value used in empresa.UsuarioId.

To solve, you can change the disabled for readonly.

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

Browser other questions tagged

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