是否以JSON格式从LINQ到SQL检索数据?

yur*_*uro 3 c# linq json entity-framework asp.net-web-api

我将数据从数据库序列化为JSON格式时遇到问题。我正在使用WebAPI 2和Entity Framework6。我已经用EF创建了一个模型。甚至创建具有内容的数据库和表。当我使用下面的代码时,键入http:// localhost:54149 / api / qr_group时出现错误

控制器:

private EfContext db = new EfContext();

// GET api/<controller>
public IEnumerable<QR_Group> GetGroups()
{
    var result = from g in db.QR_Groups
                 select g;
    return result.ToList();
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何使用Newtonsoft.Json将表与JSON格式的内容序列化。

我尝试了以下代码而不是上面的代码:

public IQueryable<QR_Group> GetGroups()
{
  var groupList = (from g in db.QR_Groups
                   select new
                   {
                     name = g.name,
                     code = g.code
                   }).AsQueryable();

  var json = JsonConvert.SerializeObject(groupList);

  return json; //error CS0029: Cannot implicitly convert type `string' to `System.Linq.IQueryable<RestApi.Models.QR_Group>'
}
Run Code Online (Sandbox Code Playgroud)

我收到错误CS0029。如何解决此问题以返回json中的数据?提醒一下:QR_Group实体具有3列(ID,名称,代码)

Sim*_*ang 5

专门针对第二个函数,JsonConvert.SerializeObject只会将任何对象序列化为JSON格式的字符串,这意味着您应该返回字符串而不是IQueryable <>。

因此,对于控制器,有很多方法可以将其返回,例如:在MVC中,如何返回字符串结果?

编辑:

以下代码将是一种可行的方式:

控制器:

private EfContext db = new EfContext();

// GET api/<controller>
public ActionResult GetGroups()
{
    var groupList = (from g in db.QR_Groups
    select new
    {
        name = g.name,
        code = g.code
    }).AsQueryable();

    return Content(JsonConvert.SerializeObject(groupList));
}
Run Code Online (Sandbox Code Playgroud)