Return Entity Framework Objects as JSON

我们两清 提交于 2020-03-19 06:45:13

问题


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:


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



来源:https://stackoverflow.com/questions/33236103/return-entity-framework-objects-as-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!