2010-05-11 30 views
0

我需要將一些與Silverlight不兼容的對象轉換爲通過WCF服務發送的模型。我試過使用ServiceKnownType,但結果仍然是對象。我可以在檢索結果後將對象投射到模型上,但我不想每次都這樣做。這是我嘗試過的一個例子。WCF服務和接口 - 結果是對象,儘管使用了ServiceKnownType

這是一個很好的方法嗎?爲什麼WCF不會將BikeModel作爲對象返回。

接口

public interface IBike 
{ 
    string BikeName { get; set;} 
} 

模型

[DataContract] 
public class BikeModel : IBike 
{ 
    [DataMember] 
    public string BikeName { get; set; } 
} 

不能在因爲MarshalObjectByRef等的Silverlight中的基類可以使用其他對象

public class Bike : IBike, UnusableBaseClass 
{ 
.... 
} 

IService1

[ServiceContract] 
[ServiceKnownType(typeof(BikeModel))] 
public interface IService1 
{ 
    [OperationContract] 
    IBike GetBike(); 
} 

服務

public class Service1 : IService1 
{ 
    public IBike GetBike() 
    { 
    Bike b = BikeManager.GetFirstBikeInTheDataBase(); 
    return b; 
    } 
} 

MainPage.xaml.cs中 -

public MainPage() 
{ 
    InitializeComponent(); 
    this.Loaded += (s, a) => 
    { 
    ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(); 
    client.GetBikeCompleted += (sender, e) => 
    { 
     var d = e.Result; 
     // this cast works 
     BikeModel model = (BikeModel)d; 
     }; 
     client.GetBikeAsync(); 

    }; 
} 

回答

0

這只是一個錯字,或者是說真的很喜歡這個模型中的?模型類應使用 [DataContract] - 而不是 [DataMember]進行裝飾。它應該是這樣的:

[DataContract] 
public class BikeModel : IBike 
{ 
    [DataMember] 
    public string BikeName { get; set; } 
} 

UPDATE:還好,那只是一個錯字。

你可以試試嗎?把你的IBike接口爲BaseBike基類:

public class BaseBike 
{ 
    string BikeName { get; set;} 
} 

,然後從您的通話

[ServiceContract] 
[ServiceKnownType(typeof(BikeModel))] 
public interface IService1 
{ 
    [OperationContract] 
    BaseBike GetBike(); 
} 

確實,在改變任何東西返回基本類型?我知道WCF對於可以序列化的內容有點挑剔 - 因爲所有序列化的代碼都必須用XML模式表示,所以不能輕鬆使用接口和/或泛型。

您可以嘗試的另一個選項是使用操作中更專注的[KnownType]屬性,而不是[ServiceKnownType]。再次 - 不知道它是否會有所幫助,我在這裏釣魚的想法....(你的東西看起來確實從.NET的角度來看 - 但WCF通信並不總是相同的世界....)

+0

我剛剛檢查了我的代碼,它是DataContract,所以它是一個錯字。我編輯了我的帖子來解決它。謝謝。 – Aligned 2010-05-11 20:28:26

+0

更改爲基本類型導致服務返回BaseBikeModel的結果。不幸的是,由於需求等原因,我無法更改Bike對象的基類。 我試圖將[KnownType(typeof(IBike))]放在BikeModel上,並沒有任何運氣。你是對的WCF並不總是按照人們所期望的方式工作。 – Aligned 2010-05-11 20:59:32

+0

@Kevin:對不起,我的意思是嘗試將[KnownType(typeof(BikeModel))]放到返回IBike的操作上。它已經返回了IBike - 所以你不需要再把它作爲一個額外的「已知類型」 – 2010-05-12 04:59:42