Performing CRUD on Relational Data (Multiple table) using Entity Framework ,RIA in Silverlight 4

No.of Views2653
Bookmarked18 times
Downloads 
Votes0
By  Manas Patnaik   On  12 Mar 2011 01:03:59
Tag : Silver Light and XAML , Data Binding
About Relational/Hierarchical data and CRUD operation against them using RIA.So its time to add some more functionality to the SOI application .
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

 

Introduction

Lots of article demos are available for RIA services but most of them are based on one table without any relational constraint. However, most of the real-time application revolves around data from multiple table and CRUD operations against them.Let’s check one of the queries I received from a reader.

“My issue is. like i have sales Invoice On save button I want to Update Sales master detail table which i can do from ria & after saving i want to update inventory table too . Is there any option i can call update inventory table using this entity.”

Basically the above query seems to be involve RIA service operation with multiple table .Well this post I am going to discuss about Relational/Hierarchical data and CRUD operation against them using RIA.So its time to add some more functionality to the SOI application .

Revisiting the SOI Demo(States Of India)

The name of the app is explanatory enough .It involved around the State Information and the Cities associated with the State.The bellow model diagram shows Entity model definition with  one to many relationship.A detailed description about SatatesOfIndia(SOI) can be found at following posts

RIA Service,Silverlight 4.0,Entity Framework,RIA Mutiple Table,Relational Data RIA

This post goes beyond traditional data operation over single table with association of data and CRUD operations over the multiple entities related to each other.

Different Types of Data Model from RIA Point of View

Although it looks like a long headed  theory post but the concept of Data Model and RIA Framework implementation is important before proceeding over the rest of article.The RIA service framework provide 3 types of Data Model feature to interact with complicated data with relationship.

image_thumb1_thumb[2]

Depending on the type of model you choose the domain operations differs. Basically, we can always edit an entity without implementing any of the above models by using separate domain operations for the entity and sending the entity collection to the client by using IncludeAttribute. However, consider the case above the State Consisting multiple cities, query to State does not load the city collection to the client side. This is the default behaviour of the Entity Framework’s Deferred Loading concept, We have to mention explicitly in the state class to load the Cities. In this post, I will demonstrate exactly the same, but it is worth knowing a little bit more about above 3models ,why and on which scenario ,we should follow above model.

Compositional ModelInheritance Data ModelData Projection /Presentation Model
One to manyEntity Derived from base EntityConsolidated objects from multiple entities
Parent Customer with multiple AddressDetail as  descendent
(State and City as in above example also but does not make a sincere composite model)
UrbanCustomer,RuralCustomer derived from base Customer EntityCustomer,AddressDetail,Address relationship
(Check with the Model from MSDN),
when the descendent entity does not make sense with out parent  
Data Operation to the descendent entity (AddressDetail)can be made by the parent (Customer) entity onlyInstead of Exposing the derived entities to the client , the base Customer can be exposed and data operation can be achieved by polymorphic Query 
Attributes used [Composite],[Include]Attributes used [KnownType] 

The implementation of a data model completely depends on the scenario, in SOI app of State.City example city can exist without state. However, an address/Invoice does not exist without a customer/person for a given ecommerce scenario and the CRUD on address/Invoice must be handled through Customer.
Although explaining all these models with same (State/City) scenario is difficult, I will try to cover each separately in future posts. So in this we will proceed with simple association of entities spanning across multiple tables for CRUD operation.

The Problem Statement / Requirement

With earlier series of articles I had demonstrated how to update , delete and Insert State entities . You can find the link to those post with links mentioned above in this article.Its obvious to get the Cities while viewing or editing a state.As in RIA,Silverlight we cant replicate the exact deferred loading concept of Entity Framework but we have a option to load the cities with adding another operation to domain contextLoadCity(int SateID).

Here i am going to explain the eager loading with RIA service .

Focusing to the SOI application , my requirement is simple

“While Navigating through the State the Cities of respective states should be loaded and While Editing or Adding a State it should allow Adding one / multiple cities to the state entity  .

 

 

 

 

Lets make changes to our UI ,

RIA Service,Silverlight 4.0,Entity Framework,RIA Mutiple Table,Relational Data RIA

Implementation

The First Step involves changing the DomainContext Entity Metadata , as mentioned earlier the state containing the City collection need to be decorated with Include attribute.This attribute specifies that the association should be part of any code-generated client entities, and that any related entities should be included when serializing results to the client. So in the StateMetadata class (DomainService_SOI.Metadata.cs) we will add following attribute to the Cities member of State entity.

Add the Attribute to the Entity Metadata:

  1. [Include]
  2. public EntityCollection<City> Cities { getset; }

In the query method, you must ensure that the associated entities are actually loaded by using the Include method on the query. This attribute can also be used to specify member projections.So we have to modify the existing query method or else have to create a additional query which will include the city entity .

Change the Query in Domain Service:

  1. public IQueryable<State> GetStatesWithCities()
  2. {
  3. return this.ObjectContext.States.Include(“Cities”);
  4. }

Lets change the the load query of  Home Page of the application which need to call the newly added query.

  1. //Use LoadOperation method to Populate the Entity Collection
  2. LoadOperation<State> statesLoadOp = dataContext.Load(dataContext.GetStatesWithCitiesQuery());
  3. statesLoadOp.Completed += new EventHandler(statesLoadOp_Completed);

On Debugging you will find the cities are loaded along with the state

RIA Service,Silverlight 4.0,Entity Framework,RIA Mutiple Table,Relational Data RIA

This much is sufficient to create a association of entities .Next we will bind the cities collection to the control for CRUD operations.

Binding descendant to control

As the SOI application intends to display all the cities of the cities of a State , where the user can read,edit or delete a city to the particular state .

RIA Service,Silverlight 4.0,Entity Framework,RIA Mutiple Table,Relational Data RIA

May be explaining the logic of the app will be like testing the reader’s patience so i left it to the reader to have look at the application Live hereand have a understanding of the flow of the application.The logic of data binding for the application follows some how is like bellow figure.

RIA Service,Silverlight 4.0,Entity Framework,RIA Mutiple Table,Relational Data RIA

Step1 and Step2 of data binding are covered with my earlier posts so we will proceed with Step3 (Assigning Data Source to List Box) and Step 4 (Using TextBox to edit and updating the City).

Binding Cities to the List Box:

RIA Service,Silverlight 4.0,Entity Framework,RIA Mutiple Table,Relational Data RIA

Assigning TextBox to the ListBox’s selected item for Editing Cities

RIA Service,Silverlight 4.0,Entity Framework,RIA Mutiple Table,Relational Data RIA

The Final Stroke

Well a little bit of of logic to submit the changes to the City Collection of the State .On final Ok button call  we need to identify weather the request is for new City or Update of a existing City.So my logic follows as bellow

  1. private void btnSaveNewCity_Click(object sender, RoutedEventArgs e)
  2. {
  3. State objState = (State)chldMainContainer.DataContext;
  4. if (!_isNewCityMode)
  5. {
  6. System.Windows.Data.BindingExpression bexp = txtNewCity.GetBindingExpression(TextBox.TextProperty);
  7. bexp.UpdateSource();
  8. }
  9. else
  10. {
  11. City objCity = new City();
  12. objCity.CityName = txtNewCity.Text;
  13. objState.Cities.Add(objCity);
  14. _isNewCityMode = false;
  15. }
  16. }
Where as the _isNewCityMode is declared as a private identifier for distingusih betwwen NewCity call or Edit of existing city.

Conclusion

This post intention is to provide complete picture for complex relation data model .Well here we have seen the basic association between entities. I haven’t touched the other ways of operations (Composite ,Inherited,Presentation) .I will try to explain those with suitable examples in future.

Source Code and Demo Link

Hosted Application : Live Sample

Source Code : StatesOfIndia_RelData.zip

 
Sign Up to vote for this article
 
About Author
 
Manas Patnaik
Occupation-Software Engineer
Company-Infosys
Member Type-Fresh
Location-India
Joined date-10 Mar 2011
Home Page-www.manaspatnaik.com
Blog Page-www.manaspatnaik.com/blog
 
 
Other popularSection articles
    For any data driven application with declarative data binding, with in XAML ,this brand new feature is the significant in many ways.Personally I remember most of the time i used to skip XAML way of binding as it lacked debugging feature.Now with Silverlight 5 my previous approach will surely take a back seat and will allow me to consider both ways equally.
    Published Date : 15/Apr/2011
    How do we create Silverlight application that follows MVVM Web Application Pattern and Performing CRUD operations in Silverlight Data Grid?
    Published Date : 17/Jun/2010
    In this article, i will show you how to implement databinding to treeview with drag and drop features in silverlight.
    Published Date : 27/Nov/2010
    ADO.Net Classes is Absent in Silverlight That why some time Developer get confused How Retrieve Data in Silvrelight Application? Silverlight Provide ServiceModel Class You Thought this Class You can Call Web services
    Published Date : 11/Jun/2010
    In this article, I have tried to demonstrate this with simple steps. What all we are going to do is Download content of XML file as string using WebClient class,Parse XML file using LINQ to XML and Bind parsed result as item source of Data Grid.
    Published Date : 28/Apr/2011
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top