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 ?
– Érik Thiago