Monday, November 7, 2011

Silverlight RIA services (without using entity framework) - The most basic example

1) Create a Silverlight (and its host ASP.NET Web App.) Project. While creating the same check on “Enable RIA Services”
2) Add a model Employee.cs in Web Project. Mark [KeyAttribute] to EmployeeId Property. This is necessary as all Entities in DomainServies should have this attribute.

3) Add a DomainService class to the Web Project and and make a method GetEmployees() returning IQueryable<Employee>. You can hard-code an IList and return list.AsQueryable<Employee>().

4) When you build the entire solution, do a “Show All Files” in Silverlight project. You will get an folder Generated_Code which has a class containing the DomainContext (with public methods converted to queries) and entities (generated from models).

5) Add the namespace for RiaControls and web Project using the following.
xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices"
             xmlns:my="clr-namespace:BasicRIAService.Web"
6) Add the RiaDataSource using the following.

<riaControls:DomainDataSource AutoLoad="True"                                                                           
                                      Name="employeeDomainDataSource"
                                      QueryName="GetEmployeesQuery"
                                      >
            <riaControls:DomainDataSource.DomainContext>
                <my:EmployeeDomainContext />
            </riaControls:DomainDataSource.DomainContext>
        </riaControls:DomainDataSource>


OR (Pick it from Static Resources)




<riaControls:DomainDataSource AutoLoad="True"                                                                           
                                      Name="employeeDomainDataSource"
                                      QueryName="GetEmployeesQuery" DomainContext="{StaticResource myContext}">
        </riaControls:DomainDataSource>

For picking it from Static Resources, you have first define it in Static Resource

<UserControl.Resources>
        <my:EmployeeDomainContext x:Key="myContext"/>
</UserControl.Resources>



7) Add a Listbox and bind to RiaDataSource using the following.
<ListBox x:Name="listEmployee" ItemsSource="{Binding ElementName=employeeDomainDataSource,Path=Data}" Width="200" Height="100">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding EmployeeId}" Margin="5,0,0,0"/>
                        <TextBlock Text="{Binding EmployeeName}" Margin="5,0,0,0"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

No comments:

Post a Comment