Those who have not referred the related post of this article can check it out : Entity Framework Posts
Till now we have understood about the working of Entity Framework and EDM.
Lets start with our first Entity Framework sample. All the feature posts along with current post uses the Northwind database. If you do not have the sample database then use the sql file of the Northwind database attached in this post.
There have been significant changes to the Entity Framework and the EDM. With the EF 4.0, some
significant improvements have been made. Along with creating an EDM from an existing database
schema (called database-first), you can now also do the following:
- Database-first: Allows you to generate your model from the existing database.
- Model-first: Allows you to start with an empty model, define your model and then
generate the database, mappings, and classes from the defined model. - Code-only: Allows you to use the Entity Framework using Plain Old CLR Objects
(POCO) entities and without an EDMX file.
Database-first approach
The database-first approach has been available since the very beginning of the EF with the release of
.NET 3.5 SP1. The model-first approach is new to Visual Studio 2010 and .NET 4.0 and allows you to
create an EDM from scratch. The code-only approach lets developers view their code as their model.
Model-first approach will be covered later on in current post and the Code-only approach will be cover in the feature post.
- Create a console application project, give it a proper name, in my case I am going to call it EF (short form of Entity Framework)
- Right click on the Solution, then select Add new item and then select ADO.NET Entity Data Model from the Templates list and click ADD
- It will ask you 2 options, create from existing database or start with empty. Select the existing database, then provide the database connection string, followed by the selection of tables, views and store procedures. For current demo I am only going to select few tables, and then press OK. The result screen looks like below
The Entity Framework automatically creates a set of classes from the model. These classes are what you will work with when you query the model, and objects will be returned that are based on these classes. Each time a change is made to the model and the model is then saved, the Entity Framework's code generator kicks in and the classes are re-created.
If you look at carefully at the generated classes you will notice that the names assigned by the EF to the Entity and Entity Sets are different, one of the cool feature of EF4 is the ability to pluralize or singularize object names
In the previous version of EF, the Entity Set Name and the Entity Name properties were both the
same whereas EF4 assigns singular names to Entity object and plural names to the EntitySets.
Model-first approach
In model first approach you do not have to select the Existing database option, but instead of that select Empty Model and then press Finish.
It ends with an empty edmx designer. Drag a Entity from the toolbox and drop it on the empty surface of the EDMX designer. Give it proper name, and then start adding the properties. It is just like the Class designer of Microsoft.NET
You can also add properties, specify association and inheritance between entities. Just for sample see the below screen:
Once you are done with your required domain model, right click on the designer, select option “Generate database from model”. This option displays “Generate Database Wizard” dialog box, just specify your database connection, and it will create a DDL file for you. Just run the file in the SQL Server, and your database gets created.
EDMX file
Close the EDMX designer, and right click on the edmx file and select “open with” option, which brings a dialog box like below:
Select the XML editor and press OK and you can see the screen like below. I have pointed the main 3 sections of the file with RED arrow.
The .edmx file is a combination of three EDM metadata files: the conceptual schema definition language (CSDL), store schema definition language (SSDL), and mapping specification language (MSL) files.
An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically. Lets start these 3 sections one by one.
-
Conceptual Schema (CSDL)
This section describes the target database schema and is written in storage schema definition language (SSDL). See a small section of our Northwind’s CSDL section.
This section defines the entity types, complex types, associations, entity containers, entity sets, and association sets in the application domain. This section is written in conceptual storage definition language (CSDL).
Schema
The outer element, Schema, defines the name of the entire model's namespace, which in this case is NorthwindModel. The namespace is defined by default to have the name of the database from which the model is derived, plus the word Model. The schema also defines an Alias, which by default is Self. This is just a nickname for the model and you can name it anything you like. There is also an xmlns namespace URI, which defines the origin of Microsoft's schema file.
EntityContainer
Within the schema is an EntityContainer named NorthwindEntities(by default). Like the namespace, this is the pattern for the default EntityContainer name using the database name plus the word Entities. You can view and change this name in the model's Properties window when you have the model open in the Designer. A conceptual model entity container maps to a storage model entity container through the EntityContainerMapping element. A storage model entity container describes the structure of the database: entity sets describe tables, association sets describe foreign key constraints, and function imports describe stored procedures in a database. It is a wrapper for EntitySets and AssociationSets and is a important entry point for querying the model. It exposes the EntitySets, and it is the EntitySets against which you will write your queries. An EntityContainer element can have zero or more of the following child elements (in the order listed):
Below figure displays the relationship of EntityContainer to its EntitySets and Entity objects
You can extend an EntityContainer element to include the contents of another EntityContainer that is within the same namespace. To include the contents of another EntityContainer, in the referencing EntityContainer element, set the value of the Extends attribute to the name of the EntityContainer element that you want to include. All child elements of the included EntityContainer element will be treated as child elements of the referencing EntityContainer element.
-
Store Schema (SSDL)
The StorageModels section of an EDMX file is a schematic representation of its associated data store. The elements of this file are similar to those of the CSDL file.
- An EntityContainer element in store schema definition language (SSDL) describes the structure of the underlying data source in an Entity Framework application: SSDL entity sets represent tables in a database, SSDL entity types (defined in EntityType elements) represent rows in a table, and association sets (defined in AssociationSet elements) represent foreign key constraints in a database. A storage model entity container maps to a conceptual model entity container through the EntityContainerMapping element.
- An EntitySet element in store schema definition language (SSDL) represents a table or view in the underlying database. An EntityType element in SSDL represents a row in the table or view. The EntityType attribute of an EntitySet element specifies the particular SSDL entity type that represents rows in an SSDL entity set. The EntitySet element can have the following child elements (in the order listed):
- Documentation (zero or one element)
- DefiningQuery (zero or one element)
- Annotation elements
- AssociationSet
- Annotation elements
The DefiningQuery allows you to execute a SQL statement directly in the underlying database. It is commonly used like a database view, but the view is defined in the storage model instead of the database. The view defined in a DefiningQuery element can be mapped to an entity type in the conceptual model through an EntitySetMapping element.
Annotation elements are custom XML elements in the storage model that provide extra metadata about the storage model. See below example.
1: <EntityType Name="Orders" xmlns:c="http://CustomNamespace">
2: <Key><PropertyRef Name="OrderId" /></Key>
3: <Property Name="OrderId" Type="int" Nullable="false"
4: c:CustomAttribute="someValue"/>
5: <Property Name="ProductId" Type="int" Nullable="false" />
6: <Property Name="Quantity" Type="int" Nullable="false" />
7: <Property Name="CustomerId" Type="int" Nullable="false" />
8: <c:CustomElement>
9: Custom data here.10: </c:CustomElement>
11: </EntityType>
Mapping Specification Language (MSL)
This section describes the mapping between the conceptual model and the target database, and is written in mapping specification language (MSL). In an Entity Framework application, mapping metadata is loaded from an .msl file (written in MSL) at build time. The Entity Framework uses mapping metadata at runtime to translate queries against the conceptual model to store-specific commands.
MSL file contains below sections:
- Mapping: This is the root element. You’ll notice that the element contains MSL (Mapping Specification Language) Space = “C-S” abbreviation. This simply signifies that the mapping is between the Conceptual and Storage schemas.
- EntityContainerMapping: This maps the entity container defined in the conceptual schema to the entity container in the storage schema. This element contains the name of the two entity containers and uses those to identify the same container names provided in the CSDL and SSDL.
- EntitySetMapping: This connects an EntitySet defined in the CSDL to an EntitySet in the SSDL.
- EntityTypeMapping: This connects an entity type and each of its properties in the CSDL to a table and column defined in the SSDL.
- Mapping Fragment: This is used for entity splitting.
- AssociationSetMapping: This identifies columns in the tables that directly correspond to EndProperty elements of related entities. Entities can only be related when a foreign key column in the data table contains a property of another table (usually a key property of another entity).
- ScalarProperty: This maps the property name of the entity type property in the CSDL to the column name of the mapped table.
Beneficial info and excellent design you got here! I want to thank you for sharing your ideas and putting the time into the stuff you publish! Great work!
ReplyDeletePretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!
ReplyDeleteNice site, nice and easy on the eyes and great content too.
ReplyDeleteIt is your turn to come up with that concept that clarifies dilemmas with so well.
ReplyDeleteI have to admit that i sometimes get bored to read the whole thing but i think that your blog can be an exception. Bravo !
ReplyDeleteThanks for the great post. Page Bookmarked
ReplyDeleteThanks for the great post. Page Bookmarked
ReplyDeleteWow this is a great resource.. I’m enjoying it.. good article
ReplyDeleteQuite a beautiful website. I recently built mine and i was looking for some ideas and you gave me a few. Did you develop the website alone?
ReplyDeleteThanks
Nobody ever proven that life is a serious thing - thus I would advise You to sit back, relax and enjoy my company in a private room, I have a strong feeling You won't regret it.
ReplyDeleteThen the second hand ticks and it's already started falling behind, it's all downhill, now.
ReplyDelete