Implementing MVP Pattern using UserControls with WCF Database Operations in Entity Framework and LINQ – PART I

 

I was recently asked by an eminent ASP.Net Developer about my opinion on the combination of the technologies mentioned in the title of this article(believe me this combination is wonderful in providing productive results). So I just got decided on that moment itself to write a blog post taking any random requirement into consideration which is the motive behind coding this article.

Okay, lets get back to work. The process flow would be like as follows –

First we create a database – ‘CustomersDB’ – with a table in it – ‘Customers’. This table Customers holds the basic data related to each and every customer. Then we create the entity model for this CustomersDB using ADO.Net Entity Framework. After that we create a WCF service with minimal end point configuration to access ServiceContracts which do basic database operations. Instead of coding the data access methods (of the class implementing ServiceContract) in traditional ADO.Net queries, we tend to use LINQ for the same. Once the service is ready, we host it using a Console App. With this we complete the backend of the article. Now we implement the MVP pattern for better separation of UI from its code with the help of presenter class. So we create an interface for both model and view and then implement them in their respective class. Finally we create a UI with some UserControls in it for adding/editing/deleting customers from the front end.

shhhhh!!! :-) looks like lengthy journey ahead. So to reduce the burden of explaining everything in detailed. I narrate only the important points of the process flow. As already our undertaken requirement is not a complex one, article readers can easily debug the code with less effort. To make the smooth flow of article I divided the entire article into parts, so that readers can skip the parts which they are already familiar.

IMPORTANT NOTES :-
  1. Combining all these different technologies at times may overkill the requirement. Especially this requirement (which we are going to work now), can be implemented in a much easier manner. In this tutorial I am trying to only narrate the possibility of the work flow, but not trying to say that this is the only way to go.
  2. Every technology we use has its own importance. Its doesn’t mean that one which got little proportion is lesser important than the others.
  3. When it comes to the explanation of MVP pattern, it would take a lengthy epistle. Although the main purpose of MVP pattern is for testability, I skipped that part in this tutorial. Testability with MVP patter will be covered in my upcoming articles. So in this article I just made a small anecdote for MVP pattern and most of the time my readers would understand the concepts in the process floe itself.

Want to skip PART I –

Implementing MVP Pattern using UserControls with WCF Database Operations in Entity Framework and LINQ – Part II

 

Implementing MVP Pattern using UserControls with WCF Database Operations in Entity Framework and LINQ – Part III

 

Okay, lets stop with the basic introduction and lets get into the business.

================================================================================================

STEP # 1 -Database Design

Create a sample ‘CustomersDB’ in VS 2010, which holds the basic info about customers.

================================================================================================

  1. Open VS 2010 -> View -> Server Explorer
  2. Right Click ‘Data Connections’ node -> Add new SQL Server Database
  3. Select a Server (from DropDownList) -> Prefer Windows Authentication -> Give a Name to the new database, here we use ‘CustomersDB’.

The database has been created, now we create a table.

  1. Expand ‘CustomersDB’ in the Server Explorer -> Right Click ‘Tables’ folder -> Select ‘Add New Table’.

Give the details of the table fields as shown below –

 CustomersDB-Definition

Save (press CTRL + SHFT + S) the table, it asks to give a table name; in this case we use ‘Customers’.

To enter sample data –

  1. Right Click ‘Customers’ table in Server Explorer -> Select -> Show Table Data

In the displayed table data pane, enter random records for testing purpose as shown below.

CustomersDB-customers-SampleData

Save the Database – This completes the Database design.

================================================================================================

STEP # 2 –Entity Model for CustomersDB using Entity Framework

To Simplify Database coding, we Use Entity Framework ORM module

================================================================================================

    1. Select New Project from File Menu option of VS 2010.
    2. Select Visual C#
    3. Select Class Library
    4. Change the name of the application in the Name text box to ‘EntityDataModelProject’
    5. Click OK

Delete the ‘Class1.cs’ file, which is placed by default.

NOTE :- Rename Solution for much more meaningful (as we are going to use the same solution throughout) – in this case it is ‘MVPwithWCF’

  1. Right Click ‘EntityDataModelProject’ Project folder in Solution Explorer, Select -> Add new Item, Select -> Data, Select -> ADO.Net Entity Data Model, Name it -> CustomersModel.edmx
  2. Select -> Generate from Database, Select -> CustomersDB.dbo in the DropDownList, also Check the checkbox to save entity ConnectionString to the Web.Config file.
  3. Check all tables; also check the two checkboxes at the bottom. (Checking the checkboxes of views and Stored Procedures is optional).
  4. Give name to the namespace -> CustomersDBModel, Click Finish.

Completed model will be as same as shown below –

CustomersDBEntityModel

Note :- App.config file will be placed in the project which constitutes the connection string to the Entity model.

This completes Entity Framework model. Remember we can do much more with this entity framework. As I already mentioned to reduce the complexity of demo, I settled with a simple model. I do advise my readers to follow up with EF designs from various sources online – especially from Julie Lerman.

================================================================================================

STEP # 3 –Creating WCF service

We code for database transactions using WCF service.

================================================================================================

  1. Right Click solution explorer on ‘MVPwithWCF’ –> Add –> New Project
  2. Select Visual C# -> WCF (also select .net framework 4.0) -> select WCF Service Library Template.
  3. Give Name -> CustomersDBServiceLibrary (also give the preferred location to save the solution).
  4. Click OK.

Delete IService1.cs and Service.cs (which are created by default). Now lets add a DataContract class – Customer.cs (right click ‘CustomersDBServiceLibrary’ in Solution explorer –> Add –> Class –> name: Customer.cs).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace CustomersDBServiceLibrary
{
    [DataContract]
    public class Customer
    {
        [DataMember]
        public int customerId { get; set; }

        [DataMember]
        public string customerName { get; set; }

        [DataMember]
        public string customerEmail { get; set; }

        [DataMember]
        public DateTime customerDOB { get; set; }
    }
}

Lets add a ServiceContract class – ICustomerService.cs (right click ‘CustomersDBServiceLibrary’ in Solution explorer –> Add –> Class –> name: ICustomerService.cs).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace CustomersDBServiceLibrary
{
    [ServiceContract]
    public interface ICustomerService
    {
        [OperationContract]
        Customer GetCustomerById(int customerId);

        [OperationContract]
        List<Customer> GetAllCustomers();

        [OperationContract]
        void InsertCustomer(Customer customerDetails);

        [OperationContract]
        void UpdateCustomer(Customer customerDetails);

        [OperationContract]
        void DeleteCustomerById(int customerId);
    }
}

Now implement the ICustomerService.cs for actual operations – add a class – CustomerService.cs (right click ‘CustomersDBServiceLibrary’ in Solution explorer –> Add –> Class –> name: CustomerService.cs).

The basic outline of the class will be as follows –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CustomersDBServiceLibrary
{
    public class CustomerService : ICustomerService
    {
        public Customer GetCustomerById(string customerID)
        {
            return null;
        }

        public List<Customer> GetALlCustomers()
        {
            return null;
        }

        public void InsertCustomer(Customer customerDetails)
        {
        }

        public void UpdateCustomer(Customer customerDetails)
        {
        }

        public void DeleteCustomerById(string customerId)
        {
        }

    }
}

 

Before actual coding against the entities, we have to refer the EntityModel (which we have created in Step #2) in this project. Not only the references, but also we have to copy the Connection String from the Entity config file to the config file of service library.

  1. Right click ‘CustomersDBServiceLibrary’ –> Add Reference –> Projects Tab –> Select ‘EntityDataModelProject’.
  2. Now Copy the <connectionStrings> tag from the app.Config file of ‘EntityDataModelProject’ to the <Configuration> section of app.Config file of ‘CustomersDBServiceLibrary’.
  3. Right click ‘CustomersDBServiceLibrary’ –> Add Reference –> .NET Tab –> Select ‘System.Data.Entity’.

This complete the Service Library preparation for accessing Entity Data Model. Now we can start coding the CustomerService.cs.

 

With this we end PART I of the tutorial.

To Follow up with the construction of CustomerService by using LINQ for database transactions and also for hosting the Service in a Console App, and there by proceeding for MVP Pattern implementation – Please follow PART II and PART III of this tutorial.

Implementing MVP Pattern using UserControls with WCF Database Operations in Entity Framework and LINQ – Part II

 

Implementing MVP Pattern using UserControls with WCF Database Operations in Entity Framework and LINQ – Part III

Disclaimer:

All coding and suggestions made in the above discussion is strictly in point of view of the author. It is neither mentioned any where nor even concluded that this is the only possible way to go with, as there will be always a chance for a new approach in achieving the same requirement (in context of programming). The above mentioned code is strictly written and explained for the sake of new comers to C# and ASP.NET world.

You may also like...

  • Magi Béla

    Dear Rami Vemula,

    I found your article very useful and elegant.
    I had some difficulties with this tutorial. I did it exactly as you wrote it, but it not work. Maybe something is missing? Could you send me the surce code, or the download link for this project?

    Thank you in advance!

  • RamiVemula

    @Magi – Can I know what you mean by not working?

  • @Coucher

    can you pls. provide the source code for the projects?

  • RamiVemula

    @Coucher – I doubt I dont have source code for that right now. You can go step by step of this tutorial and can create source code very easily.