开发者

Returning LINQ to Entities Query Result as JSON string

开发者 https://www.devze.com 2023-02-08 05:59 出处:网络
I\'m attempting to construct a web service that allows for RESTful requests to return LINQ to Entities data as JSON string data.I have no problem executing a call to the database that returns one spec

I'm attempting to construct a web service that allows for RESTful requests to return LINQ to Entities data as JSON string data. I have no problem executing a call to the database that returns one specific object:

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

Using curl, I get json data:

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"}

That being said, I have no idea how to get a string of JSON objects using the following query:

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 is a type defined as follows:

[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
}

I would just like to get a list of JSON strings as output in order to parse using JS. I've tried using a foreach loop to parse "var" into a List of MyTicket objects, calling .ToList()), etc., to no avail.

I cannot change the backend (SQL 2005/2008), but I'm trying to use a standard HTML/JS client to consume a .NET 4.0 web service. Any help would be greatly appreciated. I've spent literally days searching and reading books (especially on O'Reilly's Safari site) and I have not found a reasonable solution :(.


use 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

EDIT: Argh, the above is if you want to handle the serialization yourself.

In your example, change the return of the method from List to Ticket[] and do

return tickets.ToArray();


I wanted to add that I eventually got help to solve this. I'm not using business entities even though I'm using the Entity Framework. This may not be a wise decision, but I'm increasingly confused with Linq2SQL and Linq2EF. Here is the the code that made the above work:

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

精彩评论

暂无评论...
验证码 换一张
取 消