Franva
Franva

Reputation: 7067

How to use JSON.NET to serialize an array of objects

I remember that one of my friends told me that I can throw anything into JSON.NET and serialize them into JSON format.

    public string GetRecords(string apiKey, DateTime start, DateTime end)
    {
        var user = db.Users.SingleOrDefault(u => u.Id == apiKey);

        if (user == null)
        {
            return string.Empty;
        }

        var records = db.Histories.Where(h => h.Date >= start && h.Date <= end);

        JavaScriptSerializer s = new JavaScriptSerializer();

        return JsonConvert.SerializeObject(records);
    }

But now I got an exception:

There is already an open DataReader associated with this Command which must be closed first.

What can I do to resolve this?

Upvotes: 0

Views: 125

Answers (2)

Navyseal
Navyseal

Reputation: 901

You probably didn't enable multiple active result sets (MARS) in your config file.

Follow this link

Basically need to add

"MultipleActiveResultSets=True"

Or you could eager load as suggested by 3dd

More help here There is already an open DataReader associated with this Command which must be closed first

Upvotes: 0

3dd
3dd

Reputation: 2530

Call .ToList() on records, before passing it to JsonConvert.SerializeObject

Upvotes: 3

Related Questions