Error in making an Insert in the bank

0

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

  

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Domains_Dom.Alumni_Alumni". 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 right, what happens is when you enter an occurrence I generate this error there above. In the model of occurrence, you have to choose the name of the student to give the occurrence to him, and I think that is where the error occurs, I will put the action of create and edit to be clearer. What happens is that it tries to insert the student's ID, and in the case I'm entering his name. Anyway, I'm kind of confused and 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 am using a library called ASP.NET Awesome and in it, on of this has Select List ai, I override the Helper that has in that library called Lookup, which is a popup with a list of all the database data. And for it to work it needs to put another controller inside the class for it to work. So here, I'm going to insert the Lookup controller and the view like that. Another thing I noticed is that I have to implement a logic to save and edit the data, as it would have to load the fields with the data already registered.

Codes

StudentLookupController:

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 picks up the item chosen by the user and populates the field with the chosen value. Search - > It looks for the data in the bank 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

    
asked by anonymous 21.05.2014 / 15:27

2 answers

1

I have solved it. What happens is that I have a relationship where it gets the FK AlunoId which is the reference to table students ... For the Asp.Net Awesome to function need that where ta in the helper @ Html.LookupFor ("Student") is equal to the controller that does the manipulation, that is, this way: StudentLookupController . To solve my problem I had to put instead of Student, in the helper and in the controller, AlunoId, that would be the exact reference I was before and that is the reference to the table. So 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")
 ......

Done, solved the problem. For those who want to learn more about the Asp.Net Awesome library the website is the one . I find it very functional, but there are its peculiarities. Anyway, the answer is this!

    
22.05.2014 / 00:25
2

The error 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

@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 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>
}
    
21.05.2014 / 20:14