Recommended

Skip Navigation LinksHome / Articles / View Article

Creating applications with .NET RIA Service Part 3 - Adding DomainService class

+ Add to SilverlightShow Favorites
28 comments   /   posted by Martin Mihaylov on Mar 19, 2009
(5 votes)
Categories: Demos , Learn , Tutorials , QuickStarts

Introduction

This article continues the series of articles about the .NET RIA Services framework and Silverlight 3. The scope of it is the DomainService class, which is used to create the business logic of the application and how it combines with the ADO.NET Data Model and the Enitity framework.

Here is a link to the live demo at this stage and the source code. Note that they will be updated with each article! ;)

Here are links to the previous parts of the series:

Creating applications with .NET RIA Service  Part 1 - Introduction

Creating applications with .NET RIA Service  Part 2 - Creating the project

Creating an ADO.NET Data Model

For my application I will create the Data Model from the aspnetdb.mdf file in the App_Data folder, which contains the tables for the ASP.NET Membership:

After that choose the desired tables:

Note: In this case you can experience the following issue: if you add the aspnet_Users, aspnet_Roles and aspnet_UsersInRoles tables at one time, the aspnet_UsersInRoles table will be automatically used as Many-to-Many association between the aspnet_Users and the aspnet_Roles tables. The .NET RIA Services framework doesn't support this type of associations. So you have to add them one by one and manually configure the associations. Add the aspnet_Users first, then aspnet_UsersInRoles, which automatically creates One-to-Many association between them. At last add the aspnet_Roles, which again creates Many-to-Many association to aspnet_Users, but this time we have the aspnet_UsersInRoles table available. Now delete the Many-to-Many association and manually create association between the aspnet_UsersInRoles and the aspnet_Roles tables:

That's all regarding the ADO.NET Data Model.

Adding a DomainService class

The next step is to add a DomainService class, in which we will define our business logic. The DomainService class in the .NET RIA Services framework works only with entities, so you'll have to use a data model.

Select the server project and add a new DomainService item to it:

In the next step select which entities to be included, choose whether or not they will be edited and check the "Generate associated classes for metadata". In the metadata file an information about the entities is generated, so they could be used later on the client. The metadata file is one of the file type, which content is generated on the client:

That's it. If you now open the UsersManager.cs file you will see that CRUD methods were generated for each entity that was selected as editable. The logic in these methods can be modified to our likings. For the aspnet_Applications entity we have only Get method. As you can see there are no attributes applied to the methods so I suppose that the names of the methods could play a role when determining which method is used for update and which for delete, so I suggest not changing the names.

The metadata file

Now let's see what the metadata file can be used for. The metadata contains information about the entities that allows them to be generated on the client. Here we can apply attributes to the properties of the entities that will be available on the client too or mark whether the property to be generated on the client or not. For example:

internal sealed class aspnet_UsersMetadata
{
    // Metadata classes are not meant to be instantiated.
    private aspnet_UsersMetadata()
    {
    }
 
    public Guid UserId;
 
    [Required]
    public string UserName;
 
    public string LoweredUserName;
 
    public string MobileAlias;
 
    public bool IsAnonymous;
 
    public DateTime LastActivityDate;
 
    [Include]
    public aspnet_Applications aspnet_Applications;
 
    [Include]
    public aspnet_Membership aspnet_Membership;
 
    [Include]
    public EntityCollection<aspnet_UsersInRoles> aspnet_UsersInRoles;
 
    public EntityState EntityState;
}

The properties that describe the relations between the entities should be marked with the [Include] attribute in order to be available on the client. The UserName property is marked as [Required] and if bound to a DataFormField on the client, it will be validated as required.

Using the DomainService class on the client

Loading the Data

We have created a DomainService class on the server and now it's time to use it on the client. Let's see what functionality provides our UsersManager on the client - open the MainPage.xaml and modify the MainPage() constructor:

public MainPage()
{
    InitializeComponent();
 
    UsersManager manager = new UsersManager();
}

If you take a look at the manager you'll see that it contains a property of type EntitiyList and a load method for each entity. When you call the load method for a particular entity, a call to the get method on the server is made and the result is stored in the respective property. Of course the call is asynchronous and we have to handle the Loaded event of the manager.

Let's add a DataGrid to our MainPage.xaml and load the aspnet_Users in it:

UsersManager manager;
 
public MainPage()
{
    InitializeComponent();
 
    this.manager = new UsersManager();
    manager.Loaded += new System.EventHandler<LoadedDataEventArgs>( manager_Loaded );
}
 
private void manager_Loaded( object sender, LoadedDataEventArgs e )
{
    this.UsersGrid.ItemsSource = manager.aspnet_Users;
}

That's it!

Updating the data

The DomainService class tracks the changes to each entity in the EntityLists. To know if there are any changes, check if the HasChanges property is true, if it is, then call the SubmitChanges method or if you don't want to submit them reject them using the RejectChanges() method.

Conclusion

These were the basics of the DomainService class and there are many more things that we are going to discover in the next couple of articles. So stay tuned and if there are any questions don't hesitate to ask and I will try to answer you.

Share


Comments

Comments RSS RSS
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Rob Beasley on Mar 19, 2009 19:37
    When opening the client you have, you have to remember to add a reference to the server in order to have access to DomainService Class.
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Enrai on Mar 20, 2009 04:24
    Hi, Rob!

    Actually there is no need to add reference to the server project, as we do with the services for example. The DomainService class is available on the client thanks to the code, generated by the server in the GeneratedCode folder, that can be found in the client project. That is one of the main features of the .NET RIA Services Framework - it allows to create a link between the server and the client when we are creating our project. After that a specific parts of the server code, marked with specific attributes, or a specific files are generated on the client in the GeneratedCode folder. It's not included in the project so click on the "Show All Files" icon in order to see it. :)
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Bill on Mar 22, 2009 09:34
    When I try to do the remapping of aspnet_Roles and aspnet_UsersInRoles, I get the error

    Error 11008: Association 'aspnet_Rolesaspnet_UsersInRoles' is not mapped.

    What did I miss?
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Enrai on Mar 25, 2009 05:18

    Hi, Bill!

    I assume that you have deleted the association and tried to add a new one. In order to map it, select the association line in the model diagram and right-click it, from the context menu select Table Mapping. In the bottom of your Visual Studio a Mapping Details window should appear.

    This should do the work, but there is something else, that I forgot to mention in the article - it's about the association's name. When I left the default aspnet_Rolesaspnet_UsersInRoles name, I got an error "Unable to retrieve AssociationType for association 'aspnet_Rolesaspnet_UsersInRoles'". If you take a look at the other associations' names, you'll see that they have some wacky names. I created an empty model (which should be deleted afterwards) and added only the aspnet_Roles and aspnet_UsersInRoles tables. The association between them was generated automatically, so I took the name for my association from there. I know this some kind of strange workaround, but I am still new to the Entity Framework. It's also possible that this could be an issue between the two frameworks. If anyone can share some information about that, it would be nice. :)

    If you have more questions, Bill, just ask.

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by apocalipstik on Mar 25, 2009 15:07
    Thanks for the "Unable to retrieve AssociationType for association" workaround. I was stuck on that until I decided to read these  comments :-)
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by biofractal on Mar 26, 2009 19:07
    Is it possible to use the DomainService class to interact with POCO domain entities? Do you know of any examples of a DomainService class being used from a Domain-Driven perspective? Thank you.
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Enrai on Mar 31, 2009 07:03
    Hi, biofractal!

    Unfortunately I am still new to the Entity framework and for now there are a lot of things that I am not familiar with - the POCO entities are one of them. Surely I will catch up with the framework soon and will be able to answer your question.

    As for the second question, the .NET RIA Services is freshly released so there aren't a lot demos of it yet. If I happen to find such I will share the link! :)
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Gustavo on Apr 01, 2009 15:15
    Hi

     

    When I click to add a New Domain Service Class the "Available DataContexts/ObjectContexts" don't have any item on it. My .edmx file was created but it does not show here.

     

    What am I missing ?

     

    Thanks

     

    Gustavo

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Enrai on Apr 02, 2009 04:22

    Hi, Gistavo!

    After creating your data model, be sure to build the project. After the build the model should be available in the DomainService prompt. :) Tell me if that worked for you.
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Rachida Dukes on Apr 03, 2009 12:13

    Thanks for this series, it's very needed. I have the database attached aspnet.mdf attached to my local sql server.

    How can I add this database to App_Data folder?

    Thanks again

    Rachida Dukes

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Bill on Apr 11, 2009 19:28
    That fixed me up, Martin.

     

    Thanks!


  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by lilsteps on Apr 19, 2009 22:46

    Martin, Thanks for the application! I will look forward to the future posts!

    One question...when I add aspnet_roles table, I get 2 errors while compiling

     Problem in Mapping Fragments starting at lines 387, 408: Two entities with possibly different keys are mapped to the same row. Ensure these two mapping fragments map both ends of the AssociationSet to the corresponding columns.

    What am I doing wrong?

     

     

     

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Shorty on May 11, 2009 04:52

    Hello. Thanks for your posts. It's very Useful Posts :)

    I have a question. (sorry for my poor english)

     

    I know that 'xap file' was already installed on client side.

    If I publish a whole project including silverlight application and Web application on IIS Server,

    does the 'xap file' recognize Server's modifying codes?

    I guess the xap file size doesn't change. so, it won't be reload itself.

    Does it specified any IP Address between GenerateCode Folder(client side) and DomainserviceClass.cs(server side)?

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Domino on May 12, 2009 13:13
    What's up?  Whenever I click "OK" on the "New Domain Service Class" dialog (after adding the new "Domain Service Class" item to my web project), I get an error message in Visual Studio: "Value cannot be null.  Parameter name: namespaceName"  Then Visual Studio reverts back to the "Add New Item" dialog, and what's weird is that in this dialog, under the "Web" templates, there is no longer a "Domain Service Class" template!  I am running Windows Server 2008, and have uninstalled Alexandria.  I'd apprecaite your throughts.  Thanks dude!
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by MichaelD! on May 14, 2009 15:47
    I'm getting the same error Domino is... wtf. :P
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Jim on May 16, 2009 11:27
    Me too.
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by HES on Jun 02, 2009 17:14
    same issue (Domino / MichaelD! /Jim ) any ideas....
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by HES on Jun 02, 2009 17:17
    disregard last commnet;  "rebuild solution" works.
  • RCustom event  

    posted by Andrea on Aug 20, 2009 14:46

    Hi Would you tell me how to implement a custom server side event that the client can listen to?

    For example: I have a domainservice that load a list of objects. I would like ot notify the client everytime a single object of teh list is loaded, so i can show a loading progress on the client.

     

    Thanks

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Chakris on Oct 13, 2009 14:27

    I have a regular .NET Class Library project and with in this project, I have dbml LINQ-to-SQL and partial classes for entities and custom methods that performs CRUD opertaions. It is like DataAccess layer and this is being in use with a Win application UI. Now I want to make use of this DA Library project and want to change the UI from Win Application to SL3 application. Here I want to continue with my existing DA layer with SL3 UI.

     By the way I have my own custom User Athentication functionality. Is it possible to acheive this functionality using RIA Services and SL3 ??

    Please suggest

    Thank You.

     

     

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by miguel delgado on Nov 04, 2009 01:23

    To the users having errors with Domain Service Class and other uncontrolled errors with RIA Services:

    I installed a brand new virtual machine with vs 08 sp1, slight dev. runtime, sdk 3, tools for vs08 sp1, toolkit 3 and ria services for tools vs 08 sp1.

    Running smoothly as a baby cheek...

    Other instalations suffered from similar problems.

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Sam on Nov 04, 2009 01:45

    No matter what I do I cannot avoid this error:

    Association named xxx defined on entity type xxxx is invalid: ThisKey property named 'PeopleId' cannot be found.  

    I just add two tables which have a relationship defined in the database. The primary key (which is a foreign key in the second table) has a space in it. [People Id], but for some reason the error shows as PeopleId. I am really freustrated trying to resolve this. It compiles fine in the web project, but gives the above error when I try to build the solution.


  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Shawn on Dec 02, 2009 21:20
    I'm on a clean install of VisualStudio08 with sp1 and the newest toolkit.  I follow these steps but my "
    manager.Loaded
    " does not have a Loaded event.  Has RIA changed since this publication?
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Shaikh on Mar 09, 2010 09:11
    I'm also having difficulties as Shawn...
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by enableDeepak on Mar 26, 2010 05:14

    I get empty domain class context list where as I do have a dbml file.. details of issue: http://forums.silverlight.net/forums/t/170649.aspx

    Any help on this??

  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Dave on May 02, 2010 21:20

    Using:
    VS 2010 Premium, version 10.0.30319.1
    Silverlight 4 Toolkit April 2010
    WCF RIA Services V1.0

    This tutorial does not work! Once you add the DomainService it gives:

    The "CreateRiaClientFilesTask" task failed unexpectedly.

    Come on Microsoft, this is just trying to get the first tutorial going!!! Surely the tutorial was fully tested?

  • Entity Add precedence  

    posted by Tom Brady on May 04, 2010 16:37
    If I have a Domain Service called domainService and it contains the entities Order and Orderitem, I add three records to the Orderitem entity and one record to the Order entity in that order. Then I call domainService.SubmitChanges();  Which records will be written to the database first, this is important as each Order record will be for one or more Orderitem’s, another program will be checking the database every few minutes for new Orders so it is important that the Orderitem records are written to the database first, otherwise an Order record may be read and marked as such but some of its Orderitem records might be missed.
  • RE: Creating applications with .NET RIA Service Part 3 - Adding DomainService class  

    posted by Markus on Jun 21, 2010 21:05

    After adding the domain service class i can't build the project. There are 15 errors in the domainservice.cs file, all of them 'expecting class, delegate, enum, interface, or struct'. Even 'public IQueryable<...> Get...()' has red under it with the associated error being 'expecting class, delegate, enum...' Is my install of VS2010 corrupt? Previous attempts at building a domain service class worked just fine....Any ideas?

    Mark

Add Comment

 
 

   
  
  
   
Please add 3 and 6 and type the answer here:

Help us make SilverlightShow even better. Whether you'd like to suggest a change in the structure, content organization, section layout or any other aspect of SilverlightShow appearance - we'd love to hear from you! Need material (article, tutorial, or other) on a specific topic? Let us know and SilverlightShow content authors will work to have that prepared for you. (hide this)