Wednesday, October 27, 2010

FK Associations vs Independent Association

The main difference between these two is that in Independent Association, there is a strongly typed navigation property layered over the association, while in “FK Association” there is foreign key property on resides in the entity to associate other entity.

Initially Entity Framework supports only Independent Association, but later on it have included “FK Association”. Before Entity Framework team have introduced “FK Association”, the Independent association was called as “First class association”

The main drawback of Independent Association is that, when you have to pass a foreign entity to the target entity, then you will have to select the Foreign entity first. Which again turned in to query to the database if the entity doesn’t exists in the context. Lets see which with our Northwind example.

image

As you can see Category have many products. Now suppose if you want to add new Product with a related Category, then you must have to write something like:

using (NorthwindEntities db = new NorthwindEntities())
{
db.Products.AddObject(new Product()
{
ProductName = "Coke",
UnitPrice = 10,
Category = db.Categories.SingleOrDefault(c => c.CategoryName == "Bevrages")
});
db.SaveChanges();
}



Now if you run the profiler then you can find that the execution of above code results executing two different sql queries to the target database. The first statement is to create the product, and second statement is to relate the product with the specified category.



Later on Entity Framework have introduced “FK Association”, which contains the Foreign key property in the entity set. This is very useful in DataBinding, Dynamic Data, Concurrency Control,  ASP.NET MVC Binders, N-Tier etc.



Using the “FK Association” the same code can be written like:


using (NorthwindEntities db = new NorthwindEntities())
{
db.Products.AddObject(new Product()
{
ProductName = "Coke",
UnitPrice = 10,
CategoryID = 1
});
db.SaveChanges();
}



As you can see that the CategoryID property is  the “FK Association” property which points to the target entity. We don’t have to write select query for this anymore.



Note: This doesn’t mean that you can not write queries like the first on if you use “FK Association”, you still can write the same code in case of “FK Association” as well. Smile



How to create “FK Association”



 



To create “FK association” first create the two entities, lest say we have Product and Category entity. Then from the Toolbox, select the association and create it between the two entities. After that right click on the Association, select property and then edit the reference association. This will bring the below dialog box

image


Just pass on the property which you want to specify for foreign key property.

Saturday, October 23, 2010

Part 4: Programming for EDM

Those who have not referred the related post of this article can check it out : Entity Framework Posts

There are normally 3 ways to perform query against the Entity Data Model, which are Linq to Entities, Entity SQL and last one is Entity Client.

If you have gone thought the background knowledge of Entity Framework, then now you are ready to write queries. It is good to have background knowledge, since you can grasp easily the future posts along with the current post. Ok so now move forward to write query for Entity Framework and to do that we first need a EDM. Once we have EDM then we write code in a specific syntax, and to help in writing code we have several options. These requirements are explained in detail in below.

EDM Generate Approaches

  1. Database First Approach

    This approach is useful when the project is already developed, and Entity Framework features is needed to insert in the project. This approach creates the Entity Data Model based on the existing database. All the relations, mappings, constraints and data types are generated and derived from the existing database schema. You can also say that EF does reverse engineering from existing database and generates managed code for us.
    When you add new ADO.NET Entity Data Model item, the wizard will ask you whether you want to create EDM from existing database, or with blank database. The first option i.e. create from existing database is called the Database first approach. This is shown in below screen.
    image 

  2. Model First Approach

    Model first approach is mostly used when you have not yet created database. EF provides designing surface in which developer can create entities, complex types, can manage relationships among them etc. Once you are done with your model schema then you can generated DDL code from existing EDM.
    Lets do that. Start Visual studio, add new project ( for example I am going to create new Library project).
    Add new item called ADO.NET Entity Data Model. Select start with blank database at this time.
    image
    Press Finish, and this ends with a EF Designer screen as shown below:
    image
    Now you can create entities, can assign relationships between them using the toolbar. I am going to create two entities called “Product” and “Category” where Category have many Products relation.
    image
    Once you are done with your desired model, then you can generate the database script from the model, for that right click in the designer and select “Generate database from model” option.
    image
    Data generation wizard will popup, just provide the connection string, i.e. the destination database connection, and press Next. And you get the below screen:
    image
    Press finish, and it creates the sql file in the same project. You have to run the script on the database manually.

  3. Code First Approach

    Code First approach is introduced in Entity Framework 4.0, I will cover that in future blog, since it is the POCO (Plain Old CLR Object) feature introduced in EF 4.0

So now you know various ways to create EDM. Next we look at several syntaxes available to write query against the EDM

Type of Syntaxes:

  1. Query-Expression Syntax

    The most common syntax used with writing LINQ queries (LINQ to Entities, LINQ to SQL, etc.) is the query-expression syntax. This is simply because it is easier to read and understand. With query-expression syntax, queries are written using operators and functions.
    Lets reuse our first project which we have built in last post
    Now write the below code:

    [sourcecode language="csharp" firstline="1" padlinenumbers="true" collapse="false" gutter="true" htmlscript="false" light="false" toolbar="true" wraplines="true"]using (NorthwindEntities db = new NorthwindEntities())
    {
    var products = from product in db.Products
    select product;

    foreach (var product in products)
    Console.WriteLine("{0}\t{1}", product.ProductName, product.UnitPrice.Value);

    Console.ReadLine();
    }[/sourcecode]

    The above code will result in the below output:



    image



    Lets debug our code from the first line:



    [sourcecode language="csharp" firstline="1" padlinenumbers="true" collapse="false" gutter="true" htmlscript="false" light="false" toolbar="true" wraplines="true"]NorthwindEntities db = new NorthwindEntities()[/sourcecode]

    Over here db is our Context. This Context contains the EntitySets, which intern contains the Entities. So Products are the EntitySet, which contains the Product Entity



    var products = from product in db.Products select product;

    This is the example of the Query-Expression. They are similar to the SQL and have a rich functions to perform Projection, Filtering etc. They are known as Query Operators.



    Let say if we want to find products which have price greater then 100 and we want to sort them by unit price descending, for that we can write something like:



    [sourcecode language="csharp" firstline="1" padlinenumbers="true" collapse="false" gutter="true" htmlscript="false" light="false" toolbar="true" wraplines="true"]using (NorthwindEntities db = new NorthwindEntities())
    {
    var products = from product in db.Products
    where product.UnitPrice > 100
    orderby product.UnitPrice descending
    select product;

    foreach (var product in products)
    Console.WriteLine("{0}\t{1}", product.ProductName, product.UnitPrice.Value);

    Console.ReadLine();
    }[/sourcecode]

    The above code results in the following output:



    image



    What we have added over here the where condition and the orderby keyword to sort the result which we get in the filter based on the unit price. If you look at the code, first of your though may be that “hey the syntax is similar to T-SQL”. It looks like standard T-SQL but it is not. EF engine process this query.



    Normally when I have started programing in the Expression-based syntax, I was wondering why its starting with from"? well that seems strange at first moment. Then I did googlingLight bulb for that and here is what I found from net:




    In earlier development stage of LINQ the query statements were infect  begin with SELECT. However, the developers at Microsoft quickly realized that identifying the type that is being used up front enabled IntelliSense to provide meaningful suggestions as the rest of the query was constructed.



    According to Microsoft's Y. Alan Griver, who was very involved with the LINQ project during its early stages, the Microsoft developers jokingly referred to this syntax as "Yoda speak" when they altered the syntax for the sake of IntelliSense.






  2. Method-based Syntax



    The only difference between method based syntax and query-expression syntax is that this one is not that much easily readable. Apart from this there is no other difference like performance or behavior or feature.

    To know how Method-based syntax works you should have a bit knowledge of Lambda expressions, which were introduced in .NET Framework 3.0. Lambda expressions are anonymous functions that can contain expressions and statements. Lambda expressions use the operator =>, which is read as “goes to,” meaning that the left side of the operator specifies any input parameters while the right side of the operator holds the expression or statement block. For example, the following is a simple example of a lambda expression:



    x => x * x



    This statement can be pronounced as “x goes to x into x.” or “x goes to x square”.

    In a lambda expression the => operator has the same precedence as the = assignment.


    These Lambdas are used in method-based LINQ queries as arguments to query operator methods. For example below is a method based syntax which contains lambda expressions used as arguments to the Where query operator method.


    [sourcecode language="csharp" firstline="1" padlinenumbers="true" collapse="false" gutter="true" htmlscript="false" light="false" toolbar="true" wraplines="true"]var products = db.Products.Where(p => p.UnitPrice > 100);

    [/sourcecode]



Querying options





  1. Linq to Entities



    All the above examples we have seen are based on the LINQ to Entities. Because we have used the Entities generated by the Entity Framework. Linq to Entites is actually one of the Linq implementation. It uses ObjectQuery to construct and  process queries.



    What happens under the hood of the process is, first the query has been writing by the query syntax (as discussed above) with the use of the Entities generated by EF or the custom entities which were generated by developer using the EF API. The query has been expressed as ObjectQuery, which later on is converted in to the database provider specific query by Entity Framework. After the query is executed by the provider, the result is return back to the EF, then EF uses Object services to do materialization of the result, to construct the entites and return result back to Context.





  2. Entity SQL



    This is more complex to in understand and read compared to Linq to Entities. It is a storage-independent syntax and it looks similar to T-SQL. It was the original language designed to work with the Entity Framework to query against the EDM.


    Even though it looks similar to T-SQL, there are some differences between them. Entity SQL supports the inheritance and relationships found in an EDM, whereas in T-SQL you must use joins to work with relationships. Databases do not even have the concept of inheritance; therefore, T-SQL doesn't support that either. Entity SQL does not support the * syntax (for example SELECT *, or COUNT(*)). Another example is that T-SQL allows for ORDER BY clauses to be specified only at the topmost SELECT statement, whereas in Entity SQL you can use a nested ORDER BY expression and be placed anywhere in the query.



    A LINQ to Entities query implicitly creates an ObjectQuery. EF’s ObjectServices provides several ways to create an ObjectQuery. In case of creating ObjectQuery directly you need to use then Entity SQL to build the query expression. Lets take a look at the code below:



    [sourcecode language="csharp" firstline="1" padlinenumbers="true" collapse="false" gutter="true" htmlscript="false" light="false" toolbar="true" wraplines="true"]NorthwindEntities db = new NorthwindEntities();
    string query = "SELECT VALUE p FROM NorthwindEntities.Product AS p";
    query += " WHERE p.UnitPrice > 100";

    var products = db.CreateQuery<Product>(query);

    foreach (var product in products)
    Console.WriteLine(product.ProductName);[/sourcecode]

    As you can see over here that we have used Context ( NorthwindEntities in our case) to create ObjectQuery. The query is also similar to standard T-SQL like. It is also possible to create parameterized query. Checkout the below example.


    [sourcecode language="csharp" firstline="1" padlinenumbers="true" collapse="false" gutter="true" htmlscript="false" light="false" toolbar="true" wraplines="true"]string query = "SELECT VALUE p FROM NorthwindEntities.Product AS p";
    query += " WHERE p.UnitPrice > @unitPrice";

    var products = db.CreateQuery<Product>(query);
    products.Parameters.Add(new System.Data.Objects.ObjectParameter("unitPrice",100);

    foreach (var product in products)
    Console.WriteLine(product.ProductName); [/sourcecode]



    In above code we have added parameter for Unit Price.





  3. EntityClient



    EntityClient  is different  from LINQ to Entities and Object Services because it does not materialize objects. Instead, it streams data back to the requesting application as rows and columns in an EntityDataReader, which implements DbDataReader.  The EntityClient does not have its own language, so it uses the Entity SQL language to create its syntax, execute commands against an entity model. It has similar methods and properties like ADO.NET including connections, commands, parameters, and transactions. Let check out the example of Entity Client code:




    [sourcecode language="csharp" firstline="1" padlinenumbers="true" collapse="false" gutter="true" htmlscript="false" light="false" toolbar="true" wraplines="true"]using (EntityConnection con = new EntityConnection("name=NorthwindEntities"))
    {
    con.Open();

    string query = "SELECT VALUE p FROM NorthwindEntities.Product AS p";
    query += " WHERE p.UnitPrice > 100";

    EntityCommand cmd = con.CreateCommand();
    cmd.CommandText = query;
    using (EntityDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
    {
    while (dr.Read())
    {
    var firstname = dr.GetString(1);
    var lastname = dr.GetString(2);
    var title = dr.GetString(3);
    Console.WriteLine("{0} {1} {2}",
    title.Trim(), firstname.Trim(), lastname);
    }
    }
    con.Close();

    Console.ReadKey();
    }
    [/sourcecode]



    EntityConnection can accept EDM connection string  or MetaDataWorkSpace.



Sunday, October 17, 2010

Part 3 : Creating first EDM and the concept of EDMX file

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.

  1. 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)

    Create console project

  2. 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

    New EDM

  3. 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

    Northwind EDM

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 Angel

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.

Empty Data Model

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.

.EDMX file

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.

image

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.

  1. 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.

  2. 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>









  3. 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.




Part 2: Entity Data Model

The Entity Data Model is an Entity-Relationship data model. The central concepts in the EDM are entities and relationships. It is the layer between the Entity Framework and the database.

EDM provides the conceptual schema(CSDL), a representation of the database(SSDL), a mapping file(MSL), and access to an Entity Framework-aware ADO.NET provider for the target database. Due to EDM the Entity Framework doesn't care what database is being targeted. It provides a common means of interacting with the database, common query syntax, and a common method for sending changes back to the database. EDM uses EDMX file to manage conceptual schema, storage schema and their mappings. Check the screenshot displayed below for more details. I will provide more details on EDMX file in my next post.

We are not going to go more deep inside EDM, I am just going to provide an overview of some of the basic concepts of EDM e.g Types, Instances and Relationships

Types

  • EntityType: An EntityType defines the data objects which contains the information needed for the application perspective such as Employee, Account, things or activities relevant to the application. An Entity is an instance of an EntityType. It has a unique identity, independent existence, and forms the operational unit of consistency.
   1: <EntityType Name="Employee" Key="EmployeeId">



   2:     <Property Name="FirstName" Type="String" Nullable="false"/>



   3:     <Property Name="LastName" Type="String" Nullable="false"/>



   4:     <Property Name="EmailID" Type="String" Nullable="true"/>



   5: </EntityType>





  • Property: An EntityType can have one or more properties of the specified SimpleType, ComplexType, or RowType. Properties can be either single-valued or multi-valued. For example can be of type built in or can have type which returns array of values.


  • EntityKey: All instances of an EntityType are uniquely identified by the an EntityKey. It also helps to update entity instances and to allow entity instances to participate in relationships.


  • ComplexType: It represents a set of related information. Like EntityType, it consists of one or more properties of SimpleType, ComplexType, or RowType. However unlike EntityType, ComplexType is not associated with an EntityKey.For example Customer is one an EntityType, and Customer have address. So we can use it as a Complex property inside Customer Entity.





   1: <ComplexType Name="Address">



   2:     <Property Name="AddressLine1" Type="string"/>



   3:     <Property Name="AddressLine2" Type="string"/>



   4:     <Property Name="City" Type="string" fixedLength="30" />



   5:     <Property Name="State" Type="string"/>



   6:     <Property Name="Country" Type="int" nullable="false"/>



   7: </ComplexType>



   8: <EntityType Name="Customer" Key="CustomerId">



   9:     <Property Name="CustomerId" Type="String"/>



  10:     <Property Name="Name" Type="string" nullable="false"/>



  11:     <Property Name="Email" Type="string" nullable="true"/>



  12:     <Property Name="Address" type="Address"/>



  13: </EntityType>





  • RowType: It is an anonymous type that is structurally similar to ComplexType except that it cannot participate in type-inheritance. Two (anonymous) RowType instances are comparable if their corresponding RowTypes have the same number, sequence and type of properties.


  • RelationshipType: While EntityTypes are like nouns of a data model, RelationshipTypes are the verbs that connect those nouns. A RelationshipType is described over two or more participating EntityTypes. The EDM supports two kinds of RelationshipTypes, Association and Containment. An Association is like a peer-to-peer relationship while Containment is a parent-child relationship with specific membership semantics


  • Schema: All EDM types are contained within some namespace. The Schema concept defines a namespace that describes the scope of EDM types.



Below is a diagram of the EDM type hierarchy





Instances




  • EntitySet: An EntitySet for an EntityType holds instances of its EntityType or any of its subtypes. Multiple EntitySets may be defined for a given EntityType.For example if in your database you have two tables Orders and OrdersBackup. Suppose Orders table is only for current year and OrdersBackup is updated at the end of the year to move all current year’s orders in to OrdersBackup table. Now suppose you do not want to have different entities in your application then you can combine Ordes and OrdersBackup table in to single entity in you application called “Orders”. In this way you do not need to specify another entity for OrdersBackup table.


  • RelationshipSet: A RelationshipSet for a given relationship type may hold instances of that type. The relationship instance connects entity instances contained by the EntitySets participating in this RelationshipSet. A RelationshipSet description includes the RelationshipType and the corresponding EntitySets of the EntityTypes described in RelationshipType.


  • EntityContainer: All EDM instance-based concepts like EntitySets and RelationshipSets are defined in the scope of an EntityContainer. Users can have one or more instances of EntityContainer. An EntityContainer can reference one or more Schemas.



Relationships in EDM



While entity types are the nouns of a data model, relationships are the verbs that connect those nouns. A relationship is a link between two or more Entities. For example a “Company have Designers, Designers builds websites, one or more websites belongs to a single Clients.”



In this sentence Company, Designers, WebSites and Clients are the Entities. The Company and Designers are linked via Have relationship, similarly Designers and Websites are linked via Build relationship. The relationship concept is taken from the Entity-Relation data model.



Characterization


Relationships are primarily characterized by its degree, multiplicity, direction and kind. This section describes these terms in more detail.



Degree


The degree of a relationship is the number of EntityTypes associated with it. The most common form of relationship is a binary relationship that relates two EntityTypes, ternary relates three EntityTypes and the most general form is the n-ary relationship that can relate n EntityTypes.



Multiplicity


The multiplicity of a relationship describes the cardinality or number of instances of an EntityType that can be associated with the instances of another EntityType. The basic types of multiplicity are:



zero or one ( "0..1" ), exactly one ( “1” ), zero or more ( "*" ), one or more ( "1..*" ), exactly n ( "n" )



and last is many-to-many ( "n..m" ) where n is less than or equal to m.



Direction


Relationship can be uni-direction or bi-directional. In Uni-directional the relation is just like a read-only relationship. Two-way relationship communicate in both ways i.e. applicatin and datasource both can interchange data via two way communication relationship. A bi-directional relationship instance can be seen as connecting entity-instances in both directions. The label or name given to a relationship-end is called Role. Role names are unique within a relationship.



Kind


The relationship kind determine the characteristics of the relationship i.e. Composition, Identifying, Association, Conditional Association, Relationship Properties and Containment (it is like a parent-child relationship and is described below)




  • Conditional Association: The relationship is created based on the specified condition. The entity property is used to specify the conditional expression which determines whether the specific Entity is needed to be included in the RelationshipSet or not.


  • Relationships with Properties: A relationship with properties is still a relationship and can be used in all places where a standard relationship could be used. Specifically it does not mean that relationship-with-properties can be an end of another relationship, an end of a relationship is always an entity. We use the Association relationship to further describe the concept of relationship with properties.For example the relationship between Project and Designers can have property like the number of Designers needed in the project. The Project and Designer are EntityType





   1: <Association Name="ProjectsDesigners">



   2:     <End Type="Project" Multiplicity="1" role="Project" />



   3:     <End Type="Designer" Multiplicity="*" role="Designers" />



   4:     <Property Name="NrOfDesignersNeeded" Type="int" />



   5: </Association>





  • N-ary Relationships: A nary relationship can have more than two ends (or a degree greater than two). We use the Association relationship to further describe the concept of n-ary relationships. For example in below scenario Employee can perform tasks, tasks belongs to different Clients. So there is a n-ary relationship exists between EntityTypes Employee, Task and Client.





   1: <Association Name="EmployeesTasksCustomers">



   2:     <End Type="Employees" Multiplicity="1" role="Employee" />



   3:     <End Type="Tasks" Multiplicity="*" role="PerformedTask" />



   4:     <End Type="Customers" Multiplicity="*" role="WorkedForClient" />



   5: </Association>





  • Parent-Child Relationship (Containment): This is a kind of relationship with the following characteristics:





  • Direction: It is a bi-directional relationship with different semantics for each direction of the relationship.


  • Multiplicity: This relationship is 1 to 0..N where the cardinality of one end is always 1. For convenience, we will refer to the 1-end as the parent, and the other end as the child.


  • Exclusive membership constraint: A child EntityType may participate in multiple Containment relationships however a child entity-instance can be a member of exactly one Containment relationship-instance. In other words, a child entity-instance at all times is contained in exactly one parent entity-instance.


  • Operational Behavior: A Containment child entity-instance always lives in the scope of its parent entity-instance. As a result the Action on OnDelete operation is restricted to be Cascade or Restrict with Cascade as the default.




The following example shows the definition of a Containment relationship:





   1: <Containment Name="Parent_Child">



   2:     <End Type="Child" Multiplicity="*" role="Children" />



   3: </Containment>






Inheritance in EDM



EDM also supports inheritance. Lets say we have Designer which is derived from Employee, then we can achieve this in the EDM like below





   1: <EntityType Name="Employee" Key="EmployeeId">



   2:     <Property Name="FirstName" Type="String" Nullable="false"/>



   3:     <Property Name="LastName" Type="String" Nullable="false"/>



   4:     <Property Name="EmailID" Type="String" Nullable="true"/>



   5: </EntityType>



   6: <EntityType Name="Designer" baseType="Employee" >



   7:     <Property Name="IsFlashDesigner" Type="Boolean" Nullable="false" />



   8: </EntityType>


Part 1: Working of Entity Framework

In my previous post I have mentioned the path which we are going to follow for Entity Framework. This is the first post in the path. In this post I try to explain you guys how the Entity Framework works behind the scene.

Since we know that it is an ORM tool, so that implies that it some how provides extra features to your business entities so that they become more intelligent to know about the relations with other entities in the mode, the relationship, mapping with the database etc. That part is done by the Enity Data Model.

EDM contains your conceptual schema (CSDL), Store schema (SSDL) and mapping between Conceptual and Store schema i.e. MSL. We will dive inside the EDM in next post, for current post you treat EDM as a layer between Entity Framework and your database.

Once you have the model, then next thing you will ask that how our model gets aware of the data changes, dealing with the database etc. Well that part is done by Linq-to-Entities.

The Entity Framework uses information in the model and mapping files (which were defined in EDM) to translate object queries against entity types represented in the conceptual model into data source-specific queries. Query results are materialized into objects that the Entity Framework  manages.

Over here first Entity Framework translates the developer’s query in to Lemda expression, and after that it pass the query to the data providers. Data providers returns result back to the Entity Framework, once the result is arrived, Entity Framework uses the Object Service to get the data and construct the objects or update existing depends upon the type of the query.

The Entity Framework  provides the following ways to query a conceptual model and return objects:

  • LINQ to Entities . Provides Language-Integrated Query (LINQ) support for querying entity types that are defined in a conceptual model.
  • Entity SQL . A storage-independent dialect of SQL that works directly with entities in the conceptual model and that supports Entity Data Model  concepts. Entity SQL  is used both with object queries and queries that are executed by using the EntityClient provider. It is a SQL-like language that enables you to query conceptual models in the Entity Framework.
  • Query builder methods. These methods enable you to construct Entity SQL queries using LINQ-style query methods. Basically these are the methods which expects object query, for example WHERE, DISTINCT, GroupBy, OrderBy are different kind of builder methods.

The Entity Framework includes the EntityClient data provider. This provider manages connections, translates entity queries into data source-specific queries, and returns a data reader that the Entity Framework uses to materialize entity data into objects. When object materialization is not required, the EntityClient provider can also be used like a standard ADO.NET data provider by enabling applications to execute Entity SQL  queries and consume the returned read-only data reader.

The following diagram illustrates the Entity Framework architecture for accessing data:

 

Entity Framework Architectural Diagram

The Entity Data Model Tools can generate a class derived from ObjectContext (the base class used for querying and working with entity data as objects.) that represents the entity container in the conceptual model. This object context provides the facilities for tracking changes and managing identities, concurrency, and relationships. This class also exposes a SaveChanges method that writes inserts, updates, and deletes to the data source. Like queries, these changes are either made by commands automatically generated by the system or by stored procedures that are specified by the developer.

Data Providers

The EntityClient provider extends the ADO.NET provider model by accessing data in terms of conceptual entities and relationships. It executes queries that use Entity SQL . Entity SQL provides the underlying query language that enables EntityClient to communicate with the database.