Error making an insert in the database

Asked

Viewed 197 times

0

I am trying to save some data in the database and am getting this error:

The INSERT statement conflicted with the FOREIGN KEY Constraint "Fk_dbo.Occurrences_dbo.Alunoes_alunoid". The Conflict occurred in database "aspnet-CEF01-20140410111235", table "dbo.Alunoes", column 'Id'. The statement has been terminated.

What happens is that I have two models in my application: Students and Occurrences(1-n). The relationship is fine, what happens is it’s time to insert an occurrence generates me this mistake up there. In the occurrence model, you have to choose the name of the student to give the occurrence to him, and I think that’s where you give the error, I’ll put the create and Edit action to be clearer. What happens is that he tries to enter the student’s ID, and in this case I’m entering his name. Anyway, I’m a little confused and I wanted your help.

Actions:

 public ActionResult Create()
    {
        //ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome");
        return View();
    }
   
    // POST: /Ocorrencias/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="Id,Tipo,Causa,Descricao,AlunoId")] Ocorrencia ocorrencia)
    {
        if (ModelState.IsValid)
        {
            db.Ocorrencias.Add(ocorrencia);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome", ocorrencia.AlunoId);
        return View(ocorrencia);
    }

    // GET: /Ocorrencias/Edit/5
    public ActionResult Edit(long? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Ocorrencia ocorrencia = db.Ocorrencias.Find(id);
        if (ocorrencia == null)
        {
            return HttpNotFound();
        }
        ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome", ocorrencia.AlunoId);
        return View(ocorrencia);
    }

    // POST: /Ocorrencias/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include="Id,Tipo,Causa,Descricao,AlunoId")] Ocorrencia ocorrencia)
    {
        if (ModelState.IsValid)
        {
            db.Entry(ocorrencia).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.AlunoId = new SelectList(db.Alunos, "Id", "Nome", ocorrencia.AlunoId);
        return View(ocorrencia);
    }

And I almost forgot. I’m using a library called ASP.net Awesome and in it, on of has this Select List ai, I substitute the Helper that has in this library called Lookup, which is a popup with a list of all the data of the database. And for it to work, you need to put another controller inside the class for it to work. So here, I’m going to insert the Lookup controller and the view as it were. Another thing I realized is that, I have to implement a logic to save and to edit the data, because it would have to be loaded the fields with the data already registered.

Codes

Alunolookupcontroller:

public class AlunoLookupController : Controller
{
    private EntidadesContext db = new EntidadesContext();
    public ActionResult GetItem(int? v)
    {
        var o = db.Alunos.SingleOrDefault(f => f.Id == v) ?? new Aluno();

        return Json(new KeyContent(o.Id, o.Nome));
    }

    public ActionResult Search(string search, int page)
    {
        search = (search ?? "").ToLower().Trim();
        var lista = db.Alunos.Where(f => f.Nome.Contains(search)).ToList();
        return Json(new AjaxListResult
        {
            Items = lista.OrderBy(f => f.Nome).Skip((page - 1) * 7).Take(7).Select(o => new KeyContent(o.Id, o.Nome)),
            More = lista.Count() > page * 7
        });
    }
}

Then explaining this code: Getitem -> it takes the item chosen by the user and populates the field with the chosen value. Search -> It looks for the data in the database to put in the list for the user to choose.

Create.cshtml:

<div class="form-horizontal">
    <h4>Ocorrencia</h4>
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.Tipo, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Tipo)
            @Html.ValidationMessageFor(model => model.Tipo)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Causa, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Causa)
            @Html.ValidationMessageFor(model => model.Causa)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Descricao, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Descricao)
            @Html.ValidationMessageFor(model => model.Descricao)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.AlunoId, "AlunoId", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
           @* @Html.DropDownList("AlunoId", String.Empty)*@
            //Aqui o helper que abre um popup com a lista de todos os dados do banco pro usuário escolher !
            @Html.Awe().Lookup("Aluno")
            @Html.ValidationMessageFor(model => model.AlunoId)
        </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>

This is the Html that is generated:

<div class="awe-lookup-field">
<input name="Aluno" id="Aluno" type="hidden" class="awe-lookup">
<div class="awe-cdisplay">
    <div class="awe-display">
    </div>
</div>
<button type="button" class="awe-btn awe-openbtn">
    <span class="awe-icon awe-icon-win">
    </span>
</button>
</div>

Remembering that for an extended question I hid some parts of Create.cshtml

  • Guys, it’s urgent, could someone ?

2 answers

2

The mistake means that AlunoId is not defined. As stated in other answers, your View needs to have one of two things:

@Html.HiddenFor(model => model.AlunoId)

Or else

@Html.DropDownListFor(model => model.AlunoId, ((IEnumerable)ViewBag.Alunos).Select(option => new SelectListItem {
    Text = option.Nome, 
    Value = option.AlunoId.ToString(),
    Selected = (Model != null) && (option.AlunoId == Model.AlunoId)
}, "Selecione...")

To update the hidden use the following in your View:

@section scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            $("input[name='NomeDoCampoQueObtemAlunoId']").change(function () {
                $("input[type='hidden'][name='AlunoId']").val(this.value);
            });
        });
    </script>
}
  • 1

    Ta ai Gypsy, if you want to use the library, I found it very nice !

1


Guys I solved. What happens is that I have a relationship where I get FK Alunoid which is the reference to table students... For Asp.Net Awesome to work, you need to find where you are in the helper @Html.Lookupfor("Student") is equal to the controller doing the manipulation, that is, in this way: Alunolookupcontroller. To solve my problem I had to put Instead of Student in the helper and controller, Alunoid, which would be the exact reference that was before and which is the table reference. Then the codes would look like this:

Controller

//Onde está AlunoIdLookup, estava Aluno...., então mudei e ficou como esta abaixo
public class AlunoIdLookupController : Controller
{
   //Aqui vai as actions 
}

View

 .....
 @Html.Awe().Lookup("AlunoId")
 ......

All right, that’s it. For those who want to know more about the Asp.Net library website is this one. I think it’s very functional, but it has its peculiarities. Anyway, the answer is this !

Browser other questions tagged

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