2011-08-23 22 views
3

我在一起使用WCF服務和實體模型時遇到了問題。我從現有的數據庫創建了一個實體模型。這可以在下面顯示;爲什麼我的WCF服務不使用我的實體模型?

enter image description here

沒有任何問題,而使用任何控制檯的一個應用從哪裏來我的班「實體對象代碼生成器」。

然後,我創建WCF服務與界面下方:

[ServiceContract] 
public interface IAuthorServices 
{ 
    [OperationContract] 
    [WebGet(UriTemplate="GetNews")] 
    List<Newspaper> GetNews(); 

    [OperationContract] 
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetAuthors")] 
    List<Author> GetAuthors(); 

    [OperationContract] 
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetAuthorTexts")] 
    List<AuthorText> GetAuthorTexts(); 

    [OperationContract] 
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetTodaysTexts")] 
    List<AuthorText> GetTodaysTexts(); 

    [OperationContract] 
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetExceptions")] 
    List<KoseYazilari.Exception> GetExceptions(); 

} 

然而,當我實現服務類這些方法和運行我的客戶端應用程序,我得到了一個錯誤,如

enter image description here

我該如何擺脫這個問題?

問候, KEMAL

回答

4

標有DataContract屬性的實體?你確定它們是可序列化的嗎?

編輯:通過查看你的代碼,似乎你直接使用你的實體。這不是一個好的做法,因爲(即使你的代碼在工作),我不認爲你需要像Entity Framework自動生成的那樣的額外屬性。

在這種情況下,你應該考慮使用的DTO(數據傳輸對象),這是Newspaper類如何能是一個例子:

[DataContract] 
public class NewspaperDTO 
{ 
    public NewspaperDTO(Newspaper newspaper) 
    { 
     this.Name = newspaper.Name; 
     this.Image = newspaper.Image; 
     this.Link = newspaper.Link; 
     this.Encoding = newspaper.Encoding; 
    } 

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

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

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

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

然後在您的服務:

public List<NewspaperDTO> GetNews() 
{ 
    return entities.Newspapers.Select(a => new NewspaperDTO(a)).ToList(); 
} 

PS我注意到你的實體沒有處理(我的意思是在WCF服務中)。你應該考慮在服務的每一個方法,使用這樣的模式:

public List<NewspaperDTO> GetNews() 
{ 
    using (var entities = new MyEntities()) 
    { 
     return entities.Newspapers.Select(a => new NewspaperDTO(a)).ToList(); 
    } 
} 
+0

你可以從我的第二個截圖,它返回作者是工作的罰款,而GetNewspapers方法是行不通的GetAuthors方法見。我所看到的是,如果我從「實體模型自我跟蹤對象生成器」創建我的實體對象,一切正常。但是,這一次,當我嘗試通過webHttpBinding發佈REST服務時,我並沒有序列化/反序列化我的對象作爲json對象,即使我填充了ResponseFormat。順便說一句,它工作正常,如果我想序列化/反序列化爲XML,但再次實體對象應該由「自我跟蹤對象Gen」生成。 – kkocabiyik

+0

對於你的兩個問題,我的答案是順便說一句。 – kkocabiyik

+0

對我來說,瞭解發生的事情有點困難。即使您發佈了類圖,我也不確定背景中發生了什麼。嘗試鏈接我的問題的壓縮解決方案,我會看看;) –

相關問題