C sharp - Update Entity Framework 6 Objetos desconectados

 
Vista:
sin imagen de perfil

Update Entity Framework 6 Objetos desconectados

Publicado por Ram (1 intervención) el 22/11/2016 21:34:31
Hola, a ver si hay alguien que me pueda ayudar.

Estoy haciendo una aplicación y uso Entity Framework 6 para acceder a SQL Server.
Tengo el siguiente caso, donde quiero actualizar el valor de dos entidades:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Socio=> SocioDireccion
 
Primero llamo este método:
 
public Socio Leer(int id)
{
    Socio resultado = null;
 
    using (var context = new BDConectaClubContext())
    {
        context.Configuration.LazyLoadingEnabled = false;
        context.Configuration.ProxyCreationEnabled = false;
 
        //Usando Include linq lambda
        resultado = context.Socio
            .Include(s => s.CuentaBancaria)
            .Include(s=> s.Direcciones)
            .Include(s=>s.EMails)
            .Include(s=>s.Grupos)
            .Include(s=>s.Vocalias)
            .Where(s => s.Id == id).FirstOrDefault<Socio>();
    }
 
 
    return resultado;
 
}


La entidad Socio ya existe en la base de datos, con un SocioDireccion.
Modifico la entidad SocioDireccion añadiéndole 2 Direcciones más.

Los Ids de las entidades quedan así.

Socio
-------
Id
38 (Modificación)

SocioDireccion
---------------------
Id Socio_Id
1 38 (Modificación)
0 38 (Alta)
0 38 (Alta)



Llamo a un método que se encarga de guardar la entidad Socio.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public bool Guardar(Socio socio)
{
    int r;
 
    using (var ctx = new BDConectaClubContext())
    {
 
        ctx.Configuration.ProxyCreationEnabled = false;
        ctx.Configuration.LazyLoadingEnabled = false;
 
        if (socio.Id == 0)
        {
            ctx.Entry(socio).State = EntityState.Added;
            foreach (SocioDireccion d in socio.Direcciones)
            {
                ctx.Entry(d).State = EntityState.Added;
            }
            r = ctx.SaveChanges();
        }
        else
        {
 
            ctx.Entry(socio).State = EntityState.Modified;             //Aquí se produce el error
 
            foreach (SocioDireccion d in socio.Direcciones)
            {
                if (d.Id == 0)
                    ctx.Entry(d).State = EntityState.Added;
                else
                    ctx.Entry(d).State = EntityState.Modified;
            }
 
            r = ctx.SaveChanges();
        }
 
 
        return r > 0;
    }
}


El problema está cuando es una modificación (Socio.Id !=0)

Cuando se ejecuta esta línea
1
ctx.Entry(socio).State = EntityState.Modified;
Se produce el siguiente error:
Attaching an entity of type 'RMG.ConectaClub.Modelos.SocioDireccion' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.


Lo mas curioso es que si SocioDireccion viene de la siguiente forma no se produce el error y funciona correctamente:
Socio
-------
Id
38 (Modificación)

SocioDireccion
---------------------
Id Socio_Id
1 38 (Modificación)
0 38 (Alta)


Muchas gracias, me trae de cabeza esto. ;)
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder