ARTICLE

Code Only Design using ADO.NET Entity Framework 4.0

Posted by Srihari Chinna Articles | ADO.NET in C# July 21, 2010
This article will cover the code-only approach, which provides developers the ability to use the Entity Framework using POCO entities and without an EDMX file.
Reader Level:
Download Files:
 

This article will cover the code-only approach, which provides developers the ability to use the Entity Framework using POCO entities and without an EDMX file. This approach lets developers view code as their model. This includes topics such as
  1. Deferred or lazy loading.
  2. Complex types. 
  3. Change tracking.
  4. Foreign key association support.
The EntityClient
 
Apart from using LINQ to Entities and Entity SQL, there is one more way we can query the EDM by using EntityClient. The EntityClient provider can be used by the Entity Framework to access data. This provider uses.NET Framework data provider to access data sources, such as SQL Server. Like, the SqlClient provider for SQL Server is used by the EntityClient provider to access the SQL Server database.
 
The key to using this provider is found in the System.Data.EntityClient namespace. Although this provider operation that are performed on conceptual model, entities are translated into operations performed on physical sources, and returned results are translated from physical data sources into conceptual Entities back again. 
 
The EntityClient uses Entity SQL language to execute commands against an entity model. As such, the Entity Framework facilitates the communication and translation of Entity SQL into storage specific queries.
 
Since the Entity SQL language doesn't have specific language to query database, Entity SQL works great for the EntityClient provider. Using the EntityClient is extremely similar to using other .NET data access technologies such as the SqlClient.
 
It has got classes similar to SqlClient; EntityConnection, EntityCommand, EntityReader etc. We will see all of these classes in action.
 
Note: Please download the database scripts as well to run the sample code.
 
Create POCO Class (Data Project)
 
A. Create solution called CodeOnlyDesign.sln. I am using VSTS 2010 Ultimate trail version. Add a new class library project to the solution and name it as CodeOnlyData. As of now our primary focus is on creating POCO class.
 
1.gif
 
B. Make sure EF4FeatureCTP3.exe is installed on the machine.
 
C. Once the project is created, create class call Person.cs and Add the following code to the Person class.
 
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CodeOnlyData
{
    public class Person
    {
        public Person() { }
        public int PersonID { getset; }
        public string FirstName { getset; }
        public string MiddleName { getset; }
        public string LastName { getset; }
        public string Title { getset; }
        public DateTime BirthDate { getset; }
        public string MaritalStatus { getset; }
        public string Gender { getset; }
        public string Suffix { getset; }
        public string EmailAddress { getset; }
        public string Phone { getset; }
        public DateTime ModifiedDate { getset; }
    }
}
 
Create UI Project
 
A. We need a UI project that will consume our data project, so let's add that. From the file menu, select Add  New Project. When the Add New Project dialog opens, select ASP.NET web application template, Name this project CodeOnlyUI and click OK.
 
2.gif
 
B. Add the reference of System.Data.Entity.dll and Microsoft.Data.Entity.Ctp.dll to the UI project and CodeOnlyData project. Now we have to create the context and connections or any configuration. So create two classes namely, PersonContext.cs and PersonConfiguration.cs. 
 
C. Finally our solution looks like as follows
 
3.gif
 
D. Coding for Context class. Open the PersonContext.cs. Add the following code.
 
This class is our context and extends the ObjectContext. It represents the shape of our model and is the entry and tunnel to the database. We added a single constructor, which accepts an EntityConnection. This is simply a wrapper around the true database connection and the EF metadata.
 
This connection information is passed to the constructor when a new instance of the PersonContext is instantiated. 
 
We also declare two typed entities using the IObjectSet interface, which allow us to perform create, read, update, and delete operations. Since the ObjectSet class derives from ObjectQuery, it can also work as a query object.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.EntityClient;
using CodeOnlyData;
 
namespace CodeOnlyUI
{
    public class PersonContextObjectContext
    {
        public PersonContext(EntityConnection connection): base(connection)
        {
            DefaultContainerName = "PersonContext";
        }
        public IObjectSet<Person> Contact
        {
            get { return base.CreateObjectSet<Person>(); }
        }
    }
}
 
E. Create the Person configuration class.
 
This class holds the entire configuration for the Person class. In this class we define the property that is the primary key by using the IsIdentity() property. We also specify other property facets such as MaxLength and IsRequired. Notice that this example also illustrates that you can combine the properties on a single line instead of two separate statements.
 
This class is derived from EntityConfiguration which allows us to configure the entity properties like max length, Identity, required or optional.
 
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.EntityClient;
using Microsoft.Data.Objects;
using CodeOnlyData;
 
namespace CodeOnlyUI
{
    public class PersonConfiguration : EntityConfiguration<Person>
    {
        public PersonConfiguration()
        {
            Property(c => c.PersonID).IsIdentity();
            Property(c => c.FirstName).HasMaxLength(50);
            Property(c => c.FirstName).IsRequired();
            Property(c => c.MiddleName).HasMaxLength(50);
            Property(c => c.LastName).HasMaxLength(50);
            Property(c => c.LastName).IsRequired();
            Property(c => c.Title).HasMaxLength(8);
            Property(c => c.Gender).IsRequired();
            Property(c => c.Suffix).HasMaxLength(10);
            Property(c => c.EmailAddress).HasMaxLength(50);
            Property(c => c.Phone).HasMaxLength(25);
        }
    }
}
 
F. Now it is time to query the database using code only approach. Go to the UI project, on the default.aspx file, and add GridView and a button on the screen. Names I am leaving upto you. In my case they are going to be gvPersons and getPersons respectively.
 
G. Add the following code in getPersons event.
 
protected void getPersons_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnection conn =
            new SqlConnection(@"Data Source=BLRLXP-SCHINNA\SQLEXPRESS;Initial Catalog=CodeOnlyDataBase;Integrated Security=SSPI");
        var builder = new ContextBuilder<PersonContext>();
        builder.Configurations.Add(new PersonConfiguration());
        var context = builder.Create(conn);
        gvPersons.DataSource = context.Person;
        gvPersons.DataBind();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}
 
4.gif

Login to add your contents and source code to this article
post comment
     

@ leandro: Although I don't work with Oracle, you can look at this: http://archive.msdn.microsoft.com/EFOracleProvider

Posted by NeCroFire Aug 03, 2011

¿Do you know how connect Entity Framework 3.5 with Oracle in VS2008 SP1?¿It is possible? Thank's

Posted by leandro bacci Aug 03, 2011

plz can u add some more examples for how can the new tables be shown in the context how to make inner join between them should we use the LINQ after retreving the full data??

Posted by M Meqdadi Jun 02, 2011

That is awesome.

This is maybe a little out of scope for this article, but I'm just wondering if you could take this further to allow for DB updates? Say you need to add a new columns to table "x". If you add it in Code, how would you update table "x" in the DB to have this column?

I'm thinking maybe some sort of version system would be needed? Lets say the DB is version 1, but the App needs version 2. When the App starts it will "see" that the DB is the wrong version and then execute code to update the DB?? This doesn't seem like it's covered much.

Thanks for your replies.

Posted by NeCroFire Aug 19, 2010

Yes, it did work for me...

i had daily demos, with validations, flows and some stub data, also dynamixc screen elements based on business rules. After all i generated DB Script from there

Posted by Srihari Chinna Aug 19, 2010
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.