Serializing Entity Framework classes with JSON (Web API) without relationship

How many times have you ever tried to serialize an object of a type generated by EntityFramework.
As you know with Entity Framework the relationship between to tables are made using virtual IEnumerable.

As just you try to access to these properties, Entity Framework will load it. This is the default behavior called LazyLoading.

This behavior is a problem when you try to serialize it with Json (Web Api or other) because it will loop and load all the related entities.
Looking for a solution I found many people suggest to create a DTO class or create an anonymous type like this:

[RoutePrefix("api/Inventario")]
public class InventarioController : ApiController
{
    // GET: api/Inventario
    [Route("Modelli/{idCategoria}")]
    public IEnumerable<TAB_MODELLI_INVENTARIO> GetModelli(decimal idCategoria)
    {
        using (var db = new EFContext())
        {
            var models = db.SelectModelli(idCategoria);
            // Creating anonymous type
            return models.Select(a => new { id = a.id, prop1 = a.prop1, prop2 = a.prop2 });
        }
    }
}

I don’t like this solution because I hate write dummy code.

My preferred solution is disable lazy loading before serialize it.
This doesn’t allow Entity Framework to load the relationship while JSON.Net serialize the object

[RoutePrefix("api/Inventario")]
public class InventarioController : ApiController
{
    // GET: api/Inventario
    [Route("Modelli/{idCategoria}")]
    public IEnumerable<TAB_MODELLI_INVENTARIO> GetModelli(decimal idCategoria)
    {
        using (var db = new EFContext())
        {
            var models = db.SelectModelli(idCategoria);

            db.Configuration.LazyLoadingEnabled = false;

            return models;
        }
    }
}
Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in .Net, Asp.Net, c#, Entity Framework, MVC e contrassegnata con , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...