views:

38

answers:

3

Hi, I have

    List<Car> cars = 
        from c in myContext.Cars
        .Include("Wheels")
            .Include("Wheels.Nuts")
        orderby c.CarID

These are all EF default generated objects.

I want to turn this into JSON string containting all cars, each with its wheels, and each wheel with with its nuts, just like I would get from query.

Seems like getting back anonymous class from query is way to go, but I don't know how to get 3 level deep anon class?

Any suggestions? Any new frameworks that accomplish this?

Thanks a lot --MB

A: 

You can use AutoMapper to easily map from your EF objects to a ViewModel and then return that ViewModel as your Json. You would define your ViewModel something like this:

public class CarsViewModel
{
    public IList<Car> Cars { get; set; }

    public class Car
    {
        public int CarId { get; set; }
        public string Name { get; set; }
        // other stuff here

        public IList<CarsViewModel.Wheel> Wheels { get; set; }
    }

    public class Wheel
    {
        public int WheelId { get; set; }
        public string Brand { get; set; }
    }

    // etc. etc/
}

You would only include the properties for the things you need in your JS instead of all the columns in each table. Then you get your list of Car objects from EF just like you did and map from that to the CarsViewModel based on your AutoMapper configuration and return the CarsViewModel as the Data property of your JsonResult.

Jeff T
+2  A: 

I would recommend using JavaScriptSerializer.Serialize method:

new JavaScriptSerializer().Serialize(myContext.Cars.OrderBy(c => c.CarID).
    Select(c => new
    {
        id = c.CarID,
        vin = c.VIN,
        wheels = c.Wheels.Select(w => new
        {
            id = w.WeelID,
            nuts = w.Nuts.Select(n => new
            {
                id = n.NutID
            })
        })
    }));
Alexander Prokofyev
Thanks, that works pretty well. Other answers might work as well but this one is good enough and easy enough.I have one additional question -> can you format JavaScriptSerializer json to be human readable? Or if not can would you suggest json.net for that, seems I could use it in the same way?Thanks
Massive Boisson
A: 

you can use simple way something like this in View:

 public JsonResult GetList()
    {
        List<Car> cars = from c in myContext.Cars.Include("Wheels")
        .Include("Wheels.Nuts")orderby c.CarID
        return Json(cars.ToArray());
    }
Akyegane