开发者

EF default generated classes and JSON

开发者 https://www.devze.com 2023-01-12 10:33 出处:网络
I have List<Car> cars = from c in myContext.Cars .Include(\"Wheels\") .Include(\"Wheels.Nuts\") orderby c.CarID

I have

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

These are all EF default g开发者_高级运维enerated 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


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
            })
        })
    }));


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.


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());
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消