Return Entity Framework Objects as JSON

asp.net-mvc asp.net-mvc-4 c# entity-framework json

Question

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);
    }
1
3
10/20/2015 12:33:24 PM

Accepted Answer

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

10
3/21/2019 1:31:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow