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