我试图构建一个Web服务,允许RESTful请求返回LINQ to Entities数据作为JSON字符串数据。我必须在执行调用返回一个特定对象的数据库没有问题:返回LINQ到实体查询结果作为JSON字符串
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循环来解析“var”到MyTicket对象列表中,调用.ToList())等,无济于事。
我无法更改后端(SQL 2005/2008),但我试图使用标准的HTML/JS客户端来使用.NET 4.0 Web服务。任何帮助将不胜感激。我从字面上花了几天的搜索和读书(尤其是O'Reilly的Safari浏览器的网站),我还没有找到一个合理的解决办法:(
不幸的是改变返回值类型的结果是什么我已经得到了几乎所有我的迭代:运行时错误: “只有参数构造函数初始化和支持在LINQ to Entities中“ 我已经在几个博客中看到这是L2E的一个严重限制,但我真的不确定我可以使用哪些其他层来实现我的目标:构建一个Web服务以与SQL 2005接口/ 2008后端将由RESTful JS/HTML客户端使用。 – 2011-02-04 13:24:47