将LINQ to Entities查询结果作为JSON字符串返回

时间:2011-02-04 04:01:32

标签: linq json linq-to-entities

我试图构建一个允许RESTful请求将LINQ to Entities数据作为JSON字符串数据返回的Web服务。我对执行对返回一个特定对象的数据库的调用没有问题:

public Product GetTicket(string s)
        {
            int id = Convert.ToInt32(s);


MWAEntities context = new MWAEntities();
        var ticketEntity = (from p
                            in context.HD_TicketCurrentStatus
                            where p.Ticket_ID == id
                            select p).FirstOrDefault();
        if (ticketEntity != null)
            return TranslateTicketEntityToTicket(ticketEntity);
        else
            throw new Exception("Invalid Ticket ID");

        /**
        Product product = new Product();
        product.TicketId = 1;
        product.TicketDescription = "MyTest";
        product.TicketOperator = "Chad Cross";
        product.TicketStatus = "Work in Progress";
        return product;
        */
    }
    private Product TranslateTicketEntityToTicket(
        HD_TicketCurrentStatus ticketEntity)
    {
        Product ticket = new Product();
        ticket.TicketId = ticketEntity.Ticket_ID;
        ticket.TicketDescription = ticketEntity.F_PrivateMessage;
        ticket.TicketStatus = ticketEntity.L_Status;
        ticket.TicketOperator = ticketEntity.L_Technician;
        return ticket;
    }

使用curl,我得到json数据:

curl http://192.168.210.129:1111/ProductService/ticket/2
{"TicketDescription":"Firewall seems to be blocking her connection to www.rskco.com","TicketId":2,"TicketOperator":"Jeff","TicketStatus":"Completed"}

话虽如此,我不知道如何使用以下查询获取一串JSON对象:

public List<MyTicket> GetMyTickets(string userId)
    {
        MWAEntities context = new MWAEntities();

        /**
         * List of statuses that I consider to be "open"
         * */
        string[] statusOpen = new string[] { "Work in Progress", "Assigned", "Unassigned" };

        /**
         * List of tickets with my userID
         * */
        var tickets = (from p
                       in context.HD_TicketCurrentStatus
                       where statusOpen.Contains(p.L_Status) & p.L_Technician == userId
                       select new MyTicket(p.Ticket_ID, p.Ticket_CrtdUser, p.F_PrivateMessage, p.Ticket_CrtdDate, p.L_Status));

        return ???;
    }

MyTicket是一种定义如下的类型:

[DataContract]
public class MyTicket
{
    public MyTicket(int ticketId, string TicketCreator, string FirstPrivateMessage, DateTime TicketCreatedDate, string Status)
    {
        this.TicketId = ticketId;
        this.TicketCreator = TicketCreator;
        this.FirstPrivateMessage = FirstPrivateMessage;
        this.TicketCreatedDate = TicketCreatedDate;
        this.Status = Status;
    }
    [DataMember]
    public int TicketId { get; set; }       

    [DataMember]
    public string TicketCreator { get; set; }

    [DataMember]
    public string FirstPrivateMessage { get; set; }

    [DataMember]
    public DateTime TicketCreatedDate { get; set; }

    [DataMember]
    public string Status { get; set; }

    //p.Ticket_CrtdUser, p.Ticket_CrtdDate, p.Ticket_ID, p.F_PrivateMessage
}

我只想获得一个JSON字符串列表作为输出,以便使用JS进行解析。我尝试过使用foreach循环解析&#34; var&#34;进入MyTicket对象列表,调用.ToList())等无济于事。

我无法更改后端(SQL 2005/2008),但我尝试使用标准HTML / JS客户端来使用.NET 4.0 Web服务。任何帮助将不胜感激。我花了几天时间搜索和阅读书籍(特别是在O&#39; Reilly的Safari网站上),我找不到合理的解决方案:(。

2 个答案:

答案 0 :(得分:1)

使用Json.NET:http://james.newtonking.com/pages/json-net.aspx

using Newtonsoft.Json;

var serializer = new JsonSerializer();
serializer.Serialize(Response.Output, tickets); // per your example

编辑:唉,以上就是你想自己处理序列化。

在您的示例中,将方法的返回值从List更改为Ticket []并执行

return tickets.ToArray();

答案 1 :(得分:0)

我想补充一点,我最终得到了帮助来解决这个问题。即使我正在使用实体框架,我也没有使用商业实体。这可能不是一个明智的决定,但我越来越多地与Linq2SQL和Linq2EF混淆。以下是完成上述工作的代码:

public List<MyTicket> GetMyTickets(string userId)
    {
        MWAEntities context = new MWAEntities();

        /**
         * List of statuses that I consider to be "open"
         * */
        string[] statusOpen = new string[] { "Work in Progress", "Created"};

        var tickets = (from p
                       in context.HD_TicketCurrentStatus
                       where statusOpen.Contains(p.L_Status) & p.L_Technician == userId
                       select new MyTicket{
                           TicketId = p.Ticket_ID,
                           TicketCreatedDate = p.Ticket_CrtdDate,
                           FirstPrivateMessage = p.F_PrivateMessage,
                           Status = p.L_Status,
                           TicketCreator = p.Ticket_CrtdUser
                       });
        return tickets.ToList();
    }