Return Entity Framework Objects as JSON

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

Question

In my Controller, I'm attempting to return Entity Framework objects as JSON by using the following method:

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

return Json(results);
}

When I try to access the page /events/EventList/, I receive a server error 500. A Jquery get request also produces no results. How should the results be returned in JSON format?

Update:

This appears to function. But I require database findings.

   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

If you're going down this road, I strongly advise using a DTO to avoid any potential difficulties in the future. This answer is still receiving votes. Serializing your entity may be quicker right now, but after a year, you're going to hate yourself (I've learnt this the hard way).

New response, revised for 2018:

If you're utilizing lazy loading, the original answer given below will always work and might even be the best option. However, without slow loading, you can accomplish the following usingNewtonsoft.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 essentially ignores failures and reference loops and serializes everything that was contained in the entity framework request.

The disadvantage of this approach is that it's more difficult to manage what gets serialized. If you care about performance, you might need to start decorating your produced Entity Framework classes with a pattern like this.

// 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 response (2015):

the following response

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

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

Yours should therefore be like this.

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

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

edit

tested code was re-posted

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