Reputation: 137
I have this error and i dont know how to solve it. I searched how to solve in the internet and every time it was caused by some sql comand (which i didnt understand and its not my case).
Here is the code :
public ActionResult ConfirmarCandidatura(int id)
{
Candidatura candidatura = db.Candidaturas.Find(id);
db.Propostas.SingleOrDefault(x => x.PropostaId == candidatura.PropostaId).CandidaturaAceite = candidatura;
db.Propostas.SingleOrDefault(x => x.PropostaId == candidatura.PropostaId).CandidaturaId = candidatura.CandidaturaId;
db.Candidaturas.Find(id).CandidaturaAceite = true;
var candidaturas = db.Candidaturas.Where(x => x.PropostaId == candidatura.PropostaId);
foreach(Candidatura c in candidaturas)
{
db.Candidaturas.SingleOrDefault(u => u.CandidaturaId == c.CandidaturaId).CandidaturaRejeitada = true;
}
db.SaveChanges();
return RedirectToAction("CandidaturasRecebidas","Candidaturas");
}
Upvotes: 1
Views: 86
Reputation: 10068
When you write the following:
var candidaturas = db.Candidaturas.Where(x => x.PropostaId == candidatura.PropostaId);
you don't really close the DataReader
. Therefore when you open another DataReader
db.Candidaturas.SingleOrDefault(u =>
u.CandidaturaId == c.CandidaturaId).CandidaturaRejeitada = true;
you get an error. You should finish the first statement with .ToList()
or ToArray()
or something similar. That will give you the actual result instead of IEnumerable
As a separate comment, it's a very bad idea to write db.Propostas.SingleOrDefault(x => x.PropostaId == candidatura.PropostaId).CandidaturaAceite
(you have several like this). If null
result is not possible, use Single()
instead of SingleOrDefault()
. If it is possible, check for null
before getting child field - otherwise you will get NullException
Upvotes: 2