Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Silverlight » Silverlight 4 Linq to Sql and RIA sevice for CRUD operations

Silverlight 4 Linq to Sql and RIA sevice for CRUD operations

Silverloght 4 has lots of new fearures, for details visit Silverlight 4 . Let's start with a small application to perform CRUD operations using Linq to SQL and RIA Services.

Author Rank :
Page Views : 44856
Downloads : 1262
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Silverlight4LinqToSqlRiaServices.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Silverloght 4 has lots of new fearures, for details visit Silverlight 4 . Let's start with a small application to perform CRUD operations using Linq to
SQL and RIA Services.

Open VS 2010 and create a new project named "Silverlight4LinqToSqlRiaServices"

1.gif

The resulting screen will be

2.gif

In Silverlight project view folder add new silverlight Page "EmployeeList"

3.gif

Add Employee page title in application strings file under Assets/Resources

4.gif

On the MainPage.xaml add new hyperlink to EmployeeList page

<HyperlinkButton Style="{StaticResource LinkStyle}"
                                     NavigateUri="/EmployeeList" TargetName="ContentFrame" Content="{Binding Path=ApplicationStrings.EmployeePageTitle, Source={StaticResource ResourceWrapper
}}"/>

5.gif

Add new Linq to Sql class

6.gif

And add the Employee and Company tables and Employee_Select sp from Server Explorer

7.gif

Add new domain service

8.gif

And rebuild the solution

9.gif

10.gif

Update the EmployeeService to use the stored procedure (Employee_Select) to select records

public IList<Employee_SelectResult> Employee_Select(string employeeId, string firstName, string lastName, string companyId)
        {
            long? id = null; long? compId = null; string fName = null; string lName = null;
            id = string.IsNullOrEmpty(employeeId.Trim()) ? id : Convert.ToInt64(employeeId);
            compId = string.IsNullOrEmpty(companyId.Trim()) ? compId : Convert.ToInt64(companyId);
            fName = string.IsNullOrEmpty(firstName.Trim()) ? fName : firstName;
            lName = string.IsNullOrEmpty(lastName.Trim()) ? lName : lastName;
            return this.DataContext.Employee_Select(id, fName, lName, compId).ToList();
        }

If you try to build the solutions you may have the error saying

11.gif

I am not sure how to overcome this, but as a work around you can add [Key] before the id property in EmployeeDataClasses.designer.cs

12.gif

Now we get an error free build.

We can add the Employee_SelectResult or Employee datasource to EmployeeList.xaml from DataSources tab, I would go here with Employee datasource

13.gif

You can have the validation and descriptionViewer in EmployeeService.Metadata.cs as below=

...

internal sealed class EmployeeMetadata
        {

            // Metadata classes are not meant to be instantiated.
            private EmployeeMetadata()
            {
            }

            [Display(AutoGenerateField = false)]
            public Company Company { get; set; }

            [Display(AutoGenerateField = false)]
            public long companyId { get; set; }

            [Display(AutoGenerateField = false)]
            [Key()]
            public long id { get; set; }

            [Display(Name = "First Name", Description = "Person's first name", Order = 1)]
            [Required()]
            [StringLength(10)]
            public string firstName { get; set; }

            [Display(Name = "Last Name", Description = "Person's last name", Order = 2)]
            [Required()]
            [StringLength(10)]
            public string lastName { get; set; }

            [Display(Name = "Gender", Description = "Male/Female", Order = 3)]
            public Nullable<char> gender { get; set; }

            [Display(Name = "Active", Description = "IsActive", Order = 4)]
            public Boolean isActive { get; set; }

            [Display(AutoGenerateField = false)]
            public Binary image { get; set; }

        }
...

14.gif

Now drop the datapager from toolbox and set its datasource same as datagrid.

<sdk:DataPager Height="26" Name="dataPager1" PageSize="10" Source="{Binding ElementName=employeeDomainDataSource, Path=Data}" />

 Add Silverlight toolkit busy indicator and put the datagrid in side it.

<toolkit:BusyIndicator BusyContent="{Binding Path=ApplicationStrings.ActivityEmployeeList, Source={StaticResource ResourceWrapper}}" IsBusy="{Binding ElementName=employeeDomainDataSource, Path=DomainContext.IsLoading}">
                            <sdk:DataGrid AutoGenerateColumns="True" ItemsSource="{Binding ElementName=employeeDomainDataSource, Path=Data}" Name="employeeDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Width="400" IsReadOnly="True">

                            </sdk:DataGrid>
                        </toolkit:BusyIndicator>

So the resultant screen will be

15.gif

Lets add the dataform to EmployeeList.xaml from to edit the records. In employeeList.xaml you need to add

xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"

to include dataform. Add NewTemplate and EditTemplate to this DataForm as below

<dataForm:DataForm ItemsSource="{Binding ElementName=employeeDomainDataSource, Path=Data}" Name="dataFormEmployee" AutoEdit="False" AutoCommit="False" DeletingItem="dataFormEmployee_DeletingItem" EditEnded="dataFormEmployee_EditEnded" CurrentItemChanged="dataFormEmployee_CurrentItemChanged" AddingNewItem="dataFormEmployee_AddingNewItem" DescriptionViewerPosition="BesideContent" Header="Employee Details" AutoGenerateFields="False" IsReadOnly="False">
                                <dataForm:DataForm.ReadOnlyTemplate>
                                    <DataTemplate>
                                        <StackPanel>
                                            <dataForm:DataField Label="First Name" >
                                                <TextBox Text="{Binding firstName, Mode=TwoWay}" />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Last Name" >
                                                <TextBox Text="{Binding lastName, Mode=TwoWay}" />                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Company" >
                                                <StackPanel>
                                                    <ComboBox SelectedValuePath="id" DisplayMemberPath="name" ItemsSource="{Binding Source={StaticResource companyDomainDataSource}, Path=Data}" SelectedValue="{Binding companyId, Mode=OneWay}">
                                                        <ComboBox.ItemsPanel>
                                                            <ItemsPanelTemplate>
                                                                <VirtualizingStackPanel />
                                                            </ItemsPanelTemplate>
                                                        </ComboBox.ItemsPanel>
                                                    </ComboBox>
                                                </StackPanel>
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Gender" >
                                                <TextBox Text="{Binding gender, Mode=TwoWay,NotifyOnValidationError=True,  ValidatesOnExceptions=True }"  />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Active" >
                                                <CheckBox IsChecked="{Binding isActive, Mode=TwoWay,NotifyOnValidationError=True,  ValidatesOnExceptions=True }"  />
                                            </dataForm:DataField>
                                        </StackPanel>
                                    </DataTemplate>
                                </dataForm:DataForm.ReadOnlyTemplate>
                                <dataForm:DataForm.EditTemplate>
                                    <DataTemplate>
                                        <StackPanel>
                                            <dataForm:DataField Label="First Name" >
                                                <TextBox Text="{Binding firstName, Mode=TwoWay}" />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Last Name" >
                                                <TextBox Text="{Binding lastName, Mode=TwoWay}" />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Company" >
                                                <StackPanel>
                                                    <ComboBox SelectedValuePath="id" DisplayMemberPath="name" ItemsSource="{Binding Source={StaticResource companyDomainDataSource}, Path=Data}" SelectedValue="{Binding companyId, Mode=TwoWay}">
                                                        <ComboBox.ItemsPanel>
                                                            <ItemsPanelTemplate>
                                                                <VirtualizingStackPanel />
                                                            </ItemsPanelTemplate>
                                                        </ComboBox.ItemsPanel>
                                                    </ComboBox>
                                                </StackPanel>
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Gender" >
                                                <TextBox Text="{Binding gender, Mode=TwoWay,NotifyOnValidationError=True,  ValidatesOnExceptions=True }"  />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Active" >
                                                <CheckBox IsChecked="{Binding isActive, Mode=TwoWay,NotifyOnValidationError=True,  ValidatesOnExceptions=True }"  />
                                            </dataForm:DataField>
                                        </StackPanel>
                                    </DataTemplate>
                                </dataForm:DataForm.EditTemplate>
                                <dataForm:DataForm.NewItemTemplate>
                                    <DataTemplate>
                                        <StackPanel>
                                            <dataForm:DataField Label="First Name" >
                                                <TextBox Text="{Binding firstName, Mode=TwoWay}" />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Last Name" >
                                                <TextBox Text="{Binding lastName, Mode=TwoWay}" />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Company" >
                                                <StackPanel>
                                                    <riaControls:DomainDataSource AutoLoad="True" d:DesignData="{d:DesignInstance my1:Company, CreateList=true}" Height="0" LoadedData="companyDomainDataSource_LoadedData2"  Name="companyDomainDataSource" QueryName="GetCompaniesQuery" Width="0">
                                                        <riaControls:DomainDataSource.DomainContext>
                                                            <my:EmployeeContext />
                                                        </riaControls:DomainDataSource.DomainContext>
                                                    </riaControls:DomainDataSource>
                                                    <ComboBox SelectedValuePath="id" DisplayMemberPath="name" ItemsSource="{Binding ElementName=companyDomainDataSource, Path=Data}" SelectedValue="{Binding companyId, Mode=TwoWay}">
                                                        <ComboBox.ItemsPanel>
                                                            <ItemsPanelTemplate>
                                                                <VirtualizingStackPanel />
                                                            </ItemsPanelTemplate>
                                                        </ComboBox.ItemsPanel>
                                                    </ComboBox>
                                                </StackPanel>
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Gender" >
                                                <TextBox Text="{Binding gender, Mode=TwoWay,NotifyOnValidationError=True,  ValidatesOnExceptions=True }"  />
                                            </dataForm:DataField>
                                            <dataForm:DataField Label="Active" >
                                                <CheckBox IsChecked="{Binding isActive, Mode=TwoWay,NotifyOnValidationError=True,  ValidatesOnExceptions=True }"  />
                                            </dataForm:DataField>
                                        </StackPanel>
                                    </DataTemplate>
                                </dataForm:DataForm.NewItemTemplate>
                            </dataForm:DataForm>


Add the following events in the EmployeeList.xaml.cs

private void dataFormEmployee_DeletingItem(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this item?\nThis cannot be undone", "Delete Item", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                e.Cancel = true;
            else
                _isDeleting = true;
        }

        private void dataFormEmployee_EditEnded(object sender, DataFormEditEndedEventArgs e)
        {
            if (e.EditAction == DataFormEditAction.Commit)
            {
                if (dataFormEmployee.IsItemChanged)
                    employeeDomainDataSource.SubmitChanges();
                if (_isInserting)
                    if (employeeDomainDataSource.HasChanges)
                    {
                        employeeDomainDataSource.SubmitChanges();
                        _isInserting = false;
                    }
            }
            else
                _isInserting = false;
        }

        private void dataFormEmployee_CurrentItemChanged(object sender, EventArgs e)
        {
            if (_isDeleting)
            {
                if (employeeDomainDataSource.HasChanges)
                {
                    employeeDomainDataSource.SubmitChanges();
                    _isDeleting = false;
                }
            }
        } 

        private void dataFormEmployee_AddingNewItem(object sender, DataFormAddingNewItemEventArgs e)
        {
            _isInserting = true;
        }

And yes you are done, you have a master/detail form to edit employees that use LinqToSQL with RIA services.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Author
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Re: Data context not available in the silverlight application by har On June 15, 2010
Hi Nipun,

I ahve been following the same procedure to get mine working, but the data context that is supposed to be visible is not available i.e. the intellisense is not picking the data context in the silverlight applilcation, did u by any chance come across this issue?
thanks
Harisha
Reply | Email | Modify 
Re: Re: Data context not available in the silverlight application by chanaka On June 7, 2011
The answer is that a separate download is required -- the RIA Services Toolkit. The standard Silverlight and RIA installation does not install the LinqToSql Domain Context, the toolkit does this. http://www.microsoft.com/downloads/en/details.aspx?familyid=C4F02797-5F9E-4ACF-A7DC-C5DED53960A6&displaylang=en
Reply | Email | Modify 
error free build after adding using statement by Marcel On July 3, 2010
Hello Nipun,

To get an error free build, I had to add a using statement.

using System.ComponentModel.DataAnnotations;

and... I think you'll have to switch  "Add new domain service" with "And rebuild the solution"

When adding the dataform I get numerous errors, then I decided to download the solution and give that a try, but that isn't working too.

I get folowing eror.

Load Error:

Load operation failed for query getcompanies.... error 40 Could not open a connection to SQL Server.
Reply | Email | Modify 
Re: error free build after adding using statement by Marcel On July 3, 2010
I got the downloaded sample to work,

By deleting the Linq to sql class and creating a new one.

Because I Named my Linq to sql class EmployeeClasses, I had to change in EmployeeService.cs

EmployeeDataClassesDataContext

to

EmployeeClassesDataContext
Reply | Email | Modify 
Read Only from Stored Procedure by Annette On July 13, 2010

Thank you. Great article.  I am building a Silverlight 4 application that I want to read only using stored procedures.  Do I need the Domain Model for this a well?

Reply | Email | Modify 
re: data context not available by randy On July 21, 2010
I am having the same problem as Harisha, the LINQ to SQL data context is not available when creating the domain service class.  I have tried different projects, VB, C#, different computers, always the same result.  Has anyone solved this one?

Thanks.
Reply | Email | Modify 
Re: re: data context not available by har On July 21, 2010
hi Randy,

I don't exactly remember how i solved the issue but there was a common observation i made, if there are any errors in the application esp the .net application that hosts your silverlight app then the intellisense wouldn't show up, this is tricky because some errors wouldn't show up if u just rebuild the .net website, the best thing i can think of is try building ur silverlight application, it should show up errors if any in ur .net website.. also in your dbml.cs file make sure all the classes i.e. StordPorc/Func Results classes have [Key] attributes set up.

Give it a shot and let me know how it goes. Goodluck!!
Reply | Email | Modify 
Error with missing [Key] by rickw On October 7, 2010
Make sure your tables have a primary key set.  that's how I resolved it in my own project.
Reply | Email | Modify 
Multiple Pages same Domanin Context.Entities by Frank On October 13, 2010

I have a desperate, real life question/situation ..

 

I own your book .. and love it .. wish there was more detail about RIA (I am sure you have heard than one before).

 

1.       I created a Silverlight Business Application .. and have added 4 pages in addition to the main, home, and about pages.

2.       Each page is a completed solution ..

3.       On each “page” I go to my database for the Products download.

4.       Example:

 

Page 1.

 

I go to the SQL data and create my product context. Everything is cool.

 

When I go to Page 2, why do I have to go back to the SQL database and re download the data. I think I already have it in my DomainContext.Entities.

 

I am assuming that the data is in the domain universe, somewhere .. can I access it without having to return to the SQL database when I go to a new page?

 

 

Thanks

 

Reply | Email | Modify 
Re: Multiple Pages same Domanin Context.Entities by Frank On October 15, 2010

got the following suggestion from Kevin Dockx, a co-author of a fabulous book .. Microsoft Silverlight 4 Data and Services Cookbook:

"It appears you’re using a DomainContext instance on each page, right?  One of the ways to solve your problem would be to create some kind of local state context container, eg: a class which holds a static instance of your DomainContext.  You can access this instance from each of your pages, and reuse the product entities once they’ve been loaded – if the Products have already been loaded: don’t execute the load query again.

 Another interesting thing to look into might be “LoadBehavior”: with this (add as parameter to your load op), you can control what RIA Services should do when it returns from the server with entities which are already in your context: keep ‘em, overwrite ‘em, … "

Reply | Email | Modify 
Combobox by Andreas On April 12, 2011
Hi Nipun, I was trying to rebuild your solution but I always run into errormessages. Anything I need to do after downloading your solution and open it with VS 2010?
Reply | Email | Modify 
Good article by Nazim On June 29, 2011
this is really good article for me to start work on LINQ to SQL
Reply | Email | Modify 
good article by Kishan On August 28, 2011
Hi Nipun, Its very nice article and easy to understand. Thanks
Reply | Email | Modify 
Re: good article by Nipun On August 29, 2011
Thanks.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.