Stephane
Stephane

Reputation: 1052

Expose a object via Ria Services that implements an interface

A question about using interfaces on presentationModels with RIA services.

It is possible to expose a object via Ria Services that implements an interface?

The interface:

public interface TestInterface
{
    public int ID {get;set;}
}

We have a presentationModel :

public class TestPresentationModel : TestInterface
{
   [Key]
   public int ID {get;set;}
}

I now get a compilation error: The entity 'TestInterface' in DomainService 'SomeDomainService' does not have a key defined. Entities exposed by DomainService operations must have at least one public property marked with the KeyAttribute.

I tried to add a [Key] attribute, but then I get following error: The derived entity type 'TestPresentationModel' must be declared in a KnownTypeAttribute on the root entity 'TestInterface'.

I tried to add the [KnownTypeAttribute] attribute, but then I get following compilation error: Attribute 'KnownType' is not valid on this declaration type. It is only valid on 'class, struct' declarations.

It seems that Ria services tries to treat the interface as an entity? How can we overcome this problem?

Regards,

Stephane

Upvotes: 2

Views: 2124

Answers (2)

Jehof
Jehof

Reputation: 35544

It´s possible to use an interface for a class (viewModel) that you need on server and on client side. To to that you need to share the interface and the partial viewmodel class with the interface implementation.

In your case you need to define the classes and files as following in the server project:

File: ITestInterface.shared.cs

public interface TestInterface{
  public int ID {get;set;}
}

File: TestPresentationModel.cs

public partial class TestPresentationModel {
  [Key]
  public int ID {get;set;}
}

File: TestPresentationModel.ITestInterface.shared.cs

public partial class TestPresentationModel : ITestInterface {
   // can be empty cause the interface implementation is in TestPresentation.cs
}

Upvotes: 4

Matt Greer
Matt Greer

Reputation: 62027

One possibility is to have your client side entities implement this interface. This is what I have done. Add a file to your Silverlight app that is in the same namespace as your entities, then just extend the entities (they are all defined in partial classes):

namespace My.Model.Namespace
{
    public partial class TestPresentationModel : TestInterface
    {
        ...
    }
}

Then only your client side entities have this interface, so that may not be what you are shooting for, but it has worked well for me.

Upvotes: 0

Related Questions