views:

42

answers:

1

I need to convert some objects that are not compatible with Silverlight to models to send over a WCF service. I've tried using the ServiceKnownType, but the result is still object. I am able to cast the object to the Model after I retreive the result, but I don't want to have to do that every time. Here is an example of what I have attempted.

Is this a good approach? Why doesn't WCF return a BikeModel as an object.

Interface

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

Model

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

Other Object that can't be used in Silverlight because of MarshalObjectByRef etc in base class

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

IService1

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

Service

 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();

    };
}
A: 
marc_s
I just checked my code and it was DataContract, so it was a typo. I've edited my post to fix it. Thanks.
Kevin
Changing to the base type caused the service to return a result of BaseBikeModel. Unfortunately, I can't change the base class of the Bike object because of requirements etc.I attempted placing [KnownType(typeof(IBike))] on the BikeModel and didn't have any luck with that. You're right WCF doesn't always work the way one would expect.
Kevin
@Kevin: sorry, I meant try putting a [KnownType(typeof(BikeModel))] onto your operation that returns an IBike. It returns IBike already - so you don't need to have that as an additional "known type" again
marc_s
@marc_s: the KnownType attribute must be placed on a class (above a specific method causes a compiler error), so I tried it on the Service1 class and had the same problem.
Kevin