I have the following statements to Modify an Entity Framework object that is linked to an oracle database:
using (BASEntities context = new BASEntities())
{
//Este método comprueba que exista en caso de existir modificar
string RespuestaValidacion = ExisteConcepto(context, ConceptoTo);
CONCEPTO objConceptoBasico = new CONCEPTO
{
CODIGOCTO = ConceptoTo.CodigoConcepto,
CODIGOENTIDAD = ConceptoTo.CodigoEntidad,
demas codigo.....
};
if (string.IsNullOrEmpty(RespuestaValidacion))
{
context.CONCEPTO.Add(objConceptoBasico);
context.SaveChanges();
}
else
{
context.CONCEPTO.Attach(objConceptoBasico);
context.CONCEPTO.System.Data.Entity.EntityState.Modified(objConceptoBasico);
context.SaveChanges();
}
the method to Find if the record exists is as follows:
private string ExisteConcepto(BASEntities context, ConceptoTO ConceptoTo)
{
try
{
var qRegistro = context.SMT_CONCEPTOBASICO.Where(k =>
k.CODIGONEG == ConceptoTo.CodigoNegocio
&& k.CODIGOCTO == ConceptoTo.CodigoConcepto
&& k.IDAPLICACION == ConceptoTo.IdAplicacion
demas codigo......).FirstOrDefault();
return qRegistro == null ? "" : qRegistro.ESTADO;
}
catch (Exception error)
{
throw error;
}
}
And the mentioned error comes out:
Error 'An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.'
make the change from entity 5 to entity 6
That is a bug caused by EF validations.
To fix it you can do something like:
=================== EDITING =======================
The error occurs because you are trying to add an entity that has already been implicitly added when performing the
FirstOrDefault
in the: methodExisteConcepto
.I know 2 ways to solve the same:
ExisteConcepto
return the object instead of string and change the properties of the object (if it exists) manually or with AupoMapper (for example).Something like:
Then in your main method:
Then proceed to change the properties if the concept exists or add them if it is new:
This is the way I personally recommend.
Count
instead of aFirstOrDefault
in the method:ExisteConcepto
then you will return the number of elements that match the where criteria and in the main method you will only evaluate instead of:string.IsNullOrEmpty(RespuestaValidacion)
something like:RespuestaValidacion == 0