Return Entity Framework Objects as JSON

22,247

Edit: 2019

This answer still gets upvotes - if you're going down this road I really really suggest you just save yourself the future headaches and use a DTO. Serializing your entity is probably faster for now but (and I have learned this the hard way) - you are going to hate yourself in a years time.

New answer - updated for 2018:

The original answer below will work every time and if you're using lazy loading, it may still be the best solution. Without lazy loading though, you can do the following with Newtonsoft.JSON:

var settings = new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Error = (sender, args) =>
        {
            args.ErrorContext.Handled = true;
        },
    };

using(var context = new myContext())
{
    var myEntity = myContext.Foos.First();
    return JsonConvert.SerializeObject(myEntity, settings);
}

Which basically will serialize anything that's been included in the entity framework request, while ignoring any errors and reference loops.

The drawback to this method is that controlling what gets serialized is harder and if you're performance conscious, you may need to start decorating your generated Entity Framework classes with a pattern like

// a new partial class extending the Foo generated class, allowing us to apply an interface
[MetadataType(typeof(IFooMetaData))]
public partial class Foo : IFooMetaData
{
}

// meta data interface, forcing json ignore on Foo.Bars
public interface IFooMetaData
{
    [JsonIgnore]
    ICollection<Bar> Bars {get;set;}
}

Original answer - 2015:

Can get this response:

[
{
"OrderID": 1
},
{
"OrderID": 2
},
{
"OrderID": 3
}
]

from this:

    public JsonResult Test()
    {
        var events = new List<Event>()
        {
            new Event() {EventId = 1},
            new Event() {EventId = 2},
            new Event() {EventId = 3}
        };


        var results = events.Select(e => new
        {
            OrderID = e.EventId
        }).ToList();

        return new JsonResult() { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

So yours should be something like

    public JsonResult Test()
    {
        var results = db.Events.Select(e => new
        {
            OrderID = e.EventId
        }).ToList();

        return new JsonResult() { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

edit

re-posted with tested code

Share:
22,247
Citizen SP
Author by

Citizen SP

Web developer and MSSQL DBA. #SOreadytohelp

Updated on April 27, 2021

Comments

  • Citizen SP
    Citizen SP about 3 years

    I try to return Entity Framework Objects as Json with the following method in my Controller:

      public JsonResult EventList() {
            var results = from s in db.Events
                          select new
                          {
                              OrderID = s.EventID,
                              OrderTitle =s.EventType,
                              OrderDate = s.Title
                          };
    
    return Json(results);
    }
    

    I get a server error 500 when entering the page /events/EventList/. Also a Jquery get request returns no data. What is the correct way to return the results in Json format?

    Update:

    This seems to work. But I need results from the database.

       public ActionResult EventList() {
    
            Event test = new Event
            {
                EventID = 1,
                Title = "test",
                Description = "test"
            };
    
            return Json(new { event = test }, JsonRequestBehavior.AllowGet);
        }
    
  • Citizen SP
    Citizen SP over 8 years
    It redirects to the default error page (views/shared/error.chtml)
  • Craig
    Craig over 8 years
    Edited the answer to something I've just tried and tested
  • Yunnosch
    Yunnosch about 3 years
    Typing laughing into the answer degrades the impression of helpfulness. Also, please do the job hunting the way StackOverflow supports, not by sneaking it into answers.