简体   繁体   中英

Return Entity Framework Objects as JSON

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

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

In the controller: for example

List<categories> data = context.categories.toList();  //to here all right

now, the problem with the serialization for "data" for send the json result... i just used a struct to replace the List how???

just watch:

in the same controller ...

   struct categories_struct{
   public fieldname {get;set;}
   //the same for others firelds (same the model)
  }

now, in the ActionResult or maybe in jsonresult :

  List<categorias> data = contexto.categorias.ToList();  //I use the EF
 List<catego> data2 = new List<catego>();              //create the struct var

        foreach (categorias item in data)    //fill the struct with data
        {
            catego item2 = new catego();
            item2.codcat = item.codcat;
            item2.nomcat = item.nombrecat;
            item2.descripcion = item.descripcion;
            data2.Add(item2);
        }

        //here, Data contains all data2
        return Json(new { Data = data2 }, JsonRequestBehavior.AllowGet); 

in the view:

$.ajax({
            url: "/Categorias/getTabla",
              dataType: "JSON",
            type: "POST",
        }).done(function (respuesta) {
            var data = JSON.parse(JSON.stringify(respuesta));
            console.log(respuesta);
            alert('exito');
        }).fail(function () {
            alert('oh no, again!');
        });

///

is my solution for this problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM