2011-07-11 66 views
2

我的服务接口:返回一个WCF EF4实体JSON

[ServiceContract] 
public interface IMyService 
{ 
    [OperationContract] 
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "HelloJSON/{name}")] 
    string HelloJSON(string name); 

    [OperationContract] 
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetEmployees")] 
    List<Employee> GetEmployees(); 
} 

我的实现是:

public class MyService : IMyService 
{ 
    public string HelloJSON(string name) 
    { 
     return string.Format("Hello {0} in JSON", name); 
    } 

    public List<Employee> GetEmployees() 
    { 
     using (DBEntities ctx = new DBEntities()) 
     { 
      List<Employee> emp = new List<Employee>(); 
      emp = (from e in ctx.Employee select e).ToList(); 
      return emp; 
     } 
    } 
} 

当我打电话的第一个方法我得到的东西,如“你好在JSON佩佩”,没关系。

当我调用第二个方法并在行“return emp;”上设置断点时我得到的员工(也有从数据库6条)的名单,但在IE中我得到这个:

Internet Explorer无法显示在Firefox网页

和测试所有我得到的是一个空白页一个空白的主体,没有HTML,没有数据,也没有错误。

我想WCF不能序列化我的默认EF4实体。

编辑:

我最终的解决办法是什么(不完全)是这样的:

static string SerializeJSON<T>(T obj) { 
    JavaScriptSerializer serializer = new JavaScriptSerializer(); 
    return serializer.Serialize(obj); } 
+0

尝试在Firefox中使用Chrome或可能萤火调试客户端。例如,如果您的员工有一个循环引用,那么JSON序列化将失败。如果你能找到这个错误,这将有助于解决它。 – OpticalDelusion

+0

那么,我所做的只是一次测试,员工是该数据库中唯一的表格,我已经检查过Firebug,没有任何东西,一切看起来很正常,没有错误。谢谢你的帮助。 – Andresps2

+1

那么我没有使用WebInvoke进行JSON序列化,所以我不知道它是如何工作的,但我使用JSON序列化与我的WCF服务。我使用'return this.JSON(emp)'返回一个'JsonResult'类型,它工作正常。祝你好运。 – OpticalDelusion

回答

1

EF实体不能在默认情况下,你必须代码生成添加到它们被序列化。

请参阅这篇文章,了解如何创建Serializable实体。

称为Self Tracking entities