Thursday, 23 July 2015

What is Entity Framework?

Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.


Entity framework is useful in three scenarios.
  • First, if you already have existing database or you want to design your database ahead of other parts of the application. 
  • Second, you want to focus on your domain classes and then create the database from your domain classes. 
  • Third, you want to design your database schema on the visual designer and then create the database and classes.

Entity Framework Architecture:


EDM (Entity Data Model): EDM consists of three main parts - 

  • Conceptual model, 
  • Mapping and 
  • Storage model.
 1. Conceptual Model: The conceptual model contains the model classes and their relationships.This will be independent from your database table design.

 2. Storage Model: Storage model is the database design model which includes tables, views, stored procedures, and their relationships and keys.

3. Mapping: Mapping consists of information about how the conceptual model is mapped to the storage model.


LINQ to Entities: LINQ to Entities is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.

Entity SQL
: Entity SQL is another query language just like LINQ to Entities. However, it is a little more difficult than L2E and the developer will have to learn it separately.

Object Service:Object service is a main entry point for accessing data from the database and to return it back. Object service is responsible for materialization, which is the process of converting data returned from an entity client data provider (next layer) to an entity object structure.

Entity Client Data Provider:The main responsibility of this layer is to convert L2E or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from the database.

ADO.Net Data Provider
:This layer communicates with the database using standard ADO.Net.

Versions Set up:

Entity Framework 5.0 API was distributed in two places, in NuGet package and in .NET framework. The .NET framework 4.0/4.5 included EF core API, whereas EntityFramework.dll via NuGet package included EF 5.0 specific features.

This has been changed with EF 6.0 which is included in EntityFramework.dll only and is not dependent on .NET framework.

Create Entity Data Model(EDM):

Entity Data Model is a model that describes entities and the relationships between them. Let's create first simple EDM for  database using Visual Studio 2012 and Entity Framework 6.

1. Open Visual Studio 2012 and create a console project.


Go to PROJECT menu of visual studio -> {project name} properties - and make sure that the project's target framework is .NET Framework 4.5, as shown below.



2. Now, add Entity Data Model by right clicking on the project in the solution explorer -> Add -> click New Item and select ADO.NET Entity Data Model from popup, Give the new item the name 'School' and click Add button.



3. Entity Data Model Wizard in VS2012 opens with four options to select from: EF Designer from database for database first approach, Empty EF Designer model for model first approach, Empty Code First model and Code First from database for Code-First approach. We will focus on the database-first approach in the basic tutorials so select EF Designer from database option and clickNext.



4. You can choose from your existing DB Connections or create a new connection by clicking on the 'New Connection' button. We will use the existing DB connection to the SchoolDB Database. This will also add a connection string to your app.config file with the default suffix with DB name. You can change this if you want. Click 'Next' after you set up your DB connection.



5. In this step, you need to choose the version of Entity Framework. We will use Entity Framework 6.0 in the basic tutorials so select Entity Framework 6.0 and click Next.



Note: If you have already installed the latest version of Entity Framework using NuGet manager as shown in the Setup Environment section then this step of the wizard will no longer appear since you have already installed Entity Framework.

6. This step will display all the Tables, Views and Stored Procedures (SP) in the database. Select the Tables, Views and SPs you want, keep the default checkboxes selected and click Finish. You can change Model Namespace if you want.





Pluralize or singularize generated object names checkbox
singularizes an entityset name, if the table name in the database is plural. For example, if SchoolDB has Students table name then entityset would be singular Student. Similarly, relationships between the models will be pluralized if the table has one-to-many or many-to-many relationship with other tables. For example, Student has many-to-many relationship with Course table so Student entity set will have plural property name 'Courses' for the collection of courses.

The second checkbox, Include foreign key columns in the model, includes foreign key property explicitly to represent the foreign key. For example, Student table has one-to-many relationship with Standard table. So every student is associated with only one standard. To represent this in the model, Student entityset includes StandardId property with Standard navigation property. If this checkbox is unchecked then it will only include the Standard property, but not the StandardId in the Student entityset.

The third checkbox, Import selected stored procedures and functions into entity model, automatically creates Function Imports for the stored procedures and functions. You don't need to manually import this, as was necessary prior to Entity Framework 5.0.




7. After clicking on 'Finish', a School.edmx file will be added into your project.

Open EDM designer by double clicking on School.edmx. This displays all the entities for selected tables and the relationships between them as shown below:


EDM also adds a connection string in the config file as shown below.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="SchoolDBEntities" connectionString="metadata=res://*/SchoolDB.csdl|res://*/SchoolDB.ssdl|res://*/SchoolDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=SchoolDB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient"/>
  </connectionStrings>
</configuration>


In this way, you can create a simple EDM from your existing database.
Next: Model Browser,EntityMapping

No comments:

Post a Comment