Entity Framework: after SaveChanges returned object doesn't have children

asp.net-mvc c# entity-framework entity-framework-6

Question

When I save an object in the database and then retrieve the saved object, it shows all null subobjects.

I use Entity Framework 6 and I have always used the queries as shown in the example below and it has always worked correctly, but I do not understand why this query shows the null subobjects.

public car save_car(car data)
{
    if (data.id_car == 0)
    {                
        _contextDrag.car.Add(data);
        _contextDrag.SaveChanges();                          
    }
    else
    {
        _contextDrag.SaveChanges();
    }

    return data;
}

public car get_car(long id_car)
{            
    car data = _contextDrag.car.FirstOrDefault(a => a.idCar == id_car);            
    return data;
}
1
1
3/22/2017 12:09:07 PM

Accepted Answer

This solution I applied in my project and it works correctly.

I have used System.Data.Entity.EntityState.Detached

public car save_car(car data)
{
    if (data.id_car == 0)
    {                
        _contextDrag.car.Add(data);
        _contextDrag.SaveChanges();
        _contextDrag.Entry(data).State = System.Data.Entity.EntityState.Detached;
    }
    else
    {
       _contextDrag.SaveChanges();
    }

    return dades;
}

public car get_car(long id_car)
{            
   car data = _contextDrag.car.FirstOrDefault(a => a.idCar == id_car);            
   return data;
}
0
3/23/2017 8:33:02 AM

Popular Answer

That's because you reuse your _contextDrag for multiple operations. When you call save_car - saved car is stored inside context. When you then call get_car - the same car instance is returned. If it had all child properties null (for example is was new entity you were adding) - it will still have all child properties null, and lazy loading will not work, because it's exactly the same entity you had in save_car. As usual best way is not to ever reuse your context.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow