简体   繁体   中英

Fail to serialize C# object to Json

I was trying to serialize an object to Json and return it to my view, but it fail in these two ways:

var json = new JavaScriptSerializer().Serialize(vm);

var json = JsonConvert.SerializeObject(vm);

Here is my full code of this controller method:

public ActionResult Listagem(int id = 1)
{
    int pagina = id;

    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

    UsuariosViewModel vm = new UsuariosViewModel
    {
        Usuarios = manager.Users.Where(m => m.Ativo)
        .OrderBy(m => m.Nome)
        .Skip((pagina - 1) * UsuariosPorPagina)
        .Take(UsuariosPorPagina),

        Paginacao = new Paginacao
        {
            PaginaAtual = pagina,
            ItensPorPagina = UsuariosPorPagina
        }
    };

    vm.Paginacao.ItensTotal = manager.Users.Where(m => m.Ativo).Count();
    //var json = new JavaScriptSerializer().Serialize(vm);
    var json = JsonConvert.SerializeObject(vm);

    return Content(json);
}

And here is the error that I'm getting:

错误

I can't figure out where is the DataReader that I left opened.

Entity Framework does not execute the extension methods directly but keeps the LINQ statements in memory until they are used. Through this behavior, your Usuarios object is a non-evaluated LINQ query and will be exectued once the property is accessed (this can easily seen when debugging the code). To evaluate the query directly, you can add .ToList() to the statement, eg

UsuariosViewModel vm = new UsuariosViewModel
    {
        Usuarios = manager.Users.Where(m => m.Ativo)
        .OrderBy(m => m.Nome)
        .Skip((pagina - 1) * UsuariosPorPagina)
        .Take(UsuariosPorPagina)
        .ToList(),

        Paginacao = new Paginacao
        {
            PaginaAtual = pagina,
            ItensPorPagina = UsuariosPorPagina
        }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM