2011-07-11 63 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