简体   繁体   English

将实体框架对象作为 JSON 返回

[英]Return Entity Framework Objects as JSON

I try to return Entity Framework Objects as Json with the following method in my Controller:我尝试在我的控制器中使用以下方法将实体框架对象作为 Json 返回:

  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/.进入页面 /events/EventList/ 时出现服务器错误 500。 Also a Jquery get request returns no data.此外,Jquery 获取请求不返回任何数据。 What is the correct way to return the results in Json format?以 Json 格式返回结果的正确方法是什么?

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编辑: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.这个答案仍然得到赞成 - 如果你沿着这条路走下去,我真的建议你只是避免未来的头痛并使用 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:新答案 - 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 :无需延迟加载,您可以使用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:原始答案 - 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???现在,发送json结果的“数据”序列化问题......我只是用一个结构来替换列表如何???

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 :现在,在 ActionResult 或 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是我对这个问题的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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