entity framework

48
Entity Framework Training

Upload: betclic-everest-group-tech-team

Post on 10-May-2015

3.707 views

Category:

Technology


2 download

DESCRIPTION

This training aims to give an overview of what Entity Framework is and to provide you with some tips and tricks and links to let you improve the way you work with it.

TRANSCRIPT

Page 1: Entity Framework

Entity Framework Training

Agenda

bull A brief historyhellip

bull Whatrsquos an ORM

bull Entity Framework Architecture

bull DB First Model First and the (in)famous EDMX

bull Inheritance

bull Code First Code Second

bull Eager Lazy amp Explicit Loading

bull Performance Profiling

2 04102013 Entity Framework Training

A brief historyhellip EF releases and versioning is a bit of a mess -)

bull EF aka EF1 aka EF 35 was released with NET 35 (VS2008)

bull Basic ORM functionalities DB first only

bull EF 4 was released with NET 40 (VS2010)

bull POCO support Lazy loading

bull EF 41

bull DBContext API Code First Nuget package

bull EF 411 and then EF 42

bull Mainly bug fixes

bull EF 43

bull Code First Migration

bull EF 431

bull Bug fixes better LocalDB support

3 04102013 Entity Framework Training

A brief historyhellip MS guys were the first to admit that this versioning was not clear and thatrsquos why they rationalize how they were naming and distributing their releases

bull EF 5

bull This release can be used in Visual Studio 2010 and Visual Studio 2012 to write applications that target NET 40 and NET 45

bull But when targeting NET 45 you have enum support table-valued functions performance improvements multiple-diagrams per model

bull EF 6

bull Async Query and Save Testability improvements DbSetAddRange amp RemoveRange DbChangeTrackerHasChanges Dependency Resolution Code First Mapping to InsertUpdateDelete Stored Procedures hellip

Have a look at this post on ADO NET Blog where MS guys were calling for feedback about versioning issues

4 04102013 Entity Framework Training

Whatrsquos an ORM ORM stands for Object-Relational Mapping

According to Wikipediarsquos page

ORM is a programming technique for converting data between incompatible type systems in object-oriented programming languages This creates in effect a virtual object database that can be used from within the programming language

5 04102013 Entity Framework Training

copy2010 J Lerman

EF Architecture

6 04102013 Entity Framework Training

copy2013 MSDN

EF Architecture

7 04102013 Entity Framework Training

bull Object Services bull This is where the DBContext is which represents the session of interaction between

the applications and the data source It provides the facilities for tracking changes and managing identities concurrency and relationships And save changes towards the DB

bull EntityClient Data Provider bull 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

bull Data Providers bull This is the lowest layer which translates L2E queries via command tree to native

SQL expression and executes it against the specific DBMS system

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 2: Entity Framework

Agenda

bull A brief historyhellip

bull Whatrsquos an ORM

bull Entity Framework Architecture

bull DB First Model First and the (in)famous EDMX

bull Inheritance

bull Code First Code Second

bull Eager Lazy amp Explicit Loading

bull Performance Profiling

2 04102013 Entity Framework Training

A brief historyhellip EF releases and versioning is a bit of a mess -)

bull EF aka EF1 aka EF 35 was released with NET 35 (VS2008)

bull Basic ORM functionalities DB first only

bull EF 4 was released with NET 40 (VS2010)

bull POCO support Lazy loading

bull EF 41

bull DBContext API Code First Nuget package

bull EF 411 and then EF 42

bull Mainly bug fixes

bull EF 43

bull Code First Migration

bull EF 431

bull Bug fixes better LocalDB support

3 04102013 Entity Framework Training

A brief historyhellip MS guys were the first to admit that this versioning was not clear and thatrsquos why they rationalize how they were naming and distributing their releases

bull EF 5

bull This release can be used in Visual Studio 2010 and Visual Studio 2012 to write applications that target NET 40 and NET 45

bull But when targeting NET 45 you have enum support table-valued functions performance improvements multiple-diagrams per model

bull EF 6

bull Async Query and Save Testability improvements DbSetAddRange amp RemoveRange DbChangeTrackerHasChanges Dependency Resolution Code First Mapping to InsertUpdateDelete Stored Procedures hellip

Have a look at this post on ADO NET Blog where MS guys were calling for feedback about versioning issues

4 04102013 Entity Framework Training

Whatrsquos an ORM ORM stands for Object-Relational Mapping

According to Wikipediarsquos page

ORM is a programming technique for converting data between incompatible type systems in object-oriented programming languages This creates in effect a virtual object database that can be used from within the programming language

5 04102013 Entity Framework Training

copy2010 J Lerman

EF Architecture

6 04102013 Entity Framework Training

copy2013 MSDN

EF Architecture

7 04102013 Entity Framework Training

bull Object Services bull This is where the DBContext is which represents the session of interaction between

the applications and the data source It provides the facilities for tracking changes and managing identities concurrency and relationships And save changes towards the DB

bull EntityClient Data Provider bull 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

bull Data Providers bull This is the lowest layer which translates L2E queries via command tree to native

SQL expression and executes it against the specific DBMS system

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 3: Entity Framework

A brief historyhellip EF releases and versioning is a bit of a mess -)

bull EF aka EF1 aka EF 35 was released with NET 35 (VS2008)

bull Basic ORM functionalities DB first only

bull EF 4 was released with NET 40 (VS2010)

bull POCO support Lazy loading

bull EF 41

bull DBContext API Code First Nuget package

bull EF 411 and then EF 42

bull Mainly bug fixes

bull EF 43

bull Code First Migration

bull EF 431

bull Bug fixes better LocalDB support

3 04102013 Entity Framework Training

A brief historyhellip MS guys were the first to admit that this versioning was not clear and thatrsquos why they rationalize how they were naming and distributing their releases

bull EF 5

bull This release can be used in Visual Studio 2010 and Visual Studio 2012 to write applications that target NET 40 and NET 45

bull But when targeting NET 45 you have enum support table-valued functions performance improvements multiple-diagrams per model

bull EF 6

bull Async Query and Save Testability improvements DbSetAddRange amp RemoveRange DbChangeTrackerHasChanges Dependency Resolution Code First Mapping to InsertUpdateDelete Stored Procedures hellip

Have a look at this post on ADO NET Blog where MS guys were calling for feedback about versioning issues

4 04102013 Entity Framework Training

Whatrsquos an ORM ORM stands for Object-Relational Mapping

According to Wikipediarsquos page

ORM is a programming technique for converting data between incompatible type systems in object-oriented programming languages This creates in effect a virtual object database that can be used from within the programming language

5 04102013 Entity Framework Training

copy2010 J Lerman

EF Architecture

6 04102013 Entity Framework Training

copy2013 MSDN

EF Architecture

7 04102013 Entity Framework Training

bull Object Services bull This is where the DBContext is which represents the session of interaction between

the applications and the data source It provides the facilities for tracking changes and managing identities concurrency and relationships And save changes towards the DB

bull EntityClient Data Provider bull 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

bull Data Providers bull This is the lowest layer which translates L2E queries via command tree to native

SQL expression and executes it against the specific DBMS system

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 4: Entity Framework

A brief historyhellip MS guys were the first to admit that this versioning was not clear and thatrsquos why they rationalize how they were naming and distributing their releases

bull EF 5

bull This release can be used in Visual Studio 2010 and Visual Studio 2012 to write applications that target NET 40 and NET 45

bull But when targeting NET 45 you have enum support table-valued functions performance improvements multiple-diagrams per model

bull EF 6

bull Async Query and Save Testability improvements DbSetAddRange amp RemoveRange DbChangeTrackerHasChanges Dependency Resolution Code First Mapping to InsertUpdateDelete Stored Procedures hellip

Have a look at this post on ADO NET Blog where MS guys were calling for feedback about versioning issues

4 04102013 Entity Framework Training

Whatrsquos an ORM ORM stands for Object-Relational Mapping

According to Wikipediarsquos page

ORM is a programming technique for converting data between incompatible type systems in object-oriented programming languages This creates in effect a virtual object database that can be used from within the programming language

5 04102013 Entity Framework Training

copy2010 J Lerman

EF Architecture

6 04102013 Entity Framework Training

copy2013 MSDN

EF Architecture

7 04102013 Entity Framework Training

bull Object Services bull This is where the DBContext is which represents the session of interaction between

the applications and the data source It provides the facilities for tracking changes and managing identities concurrency and relationships And save changes towards the DB

bull EntityClient Data Provider bull 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

bull Data Providers bull This is the lowest layer which translates L2E queries via command tree to native

SQL expression and executes it against the specific DBMS system

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 5: Entity Framework

Whatrsquos an ORM ORM stands for Object-Relational Mapping

According to Wikipediarsquos page

ORM is a programming technique for converting data between incompatible type systems in object-oriented programming languages This creates in effect a virtual object database that can be used from within the programming language

5 04102013 Entity Framework Training

copy2010 J Lerman

EF Architecture

6 04102013 Entity Framework Training

copy2013 MSDN

EF Architecture

7 04102013 Entity Framework Training

bull Object Services bull This is where the DBContext is which represents the session of interaction between

the applications and the data source It provides the facilities for tracking changes and managing identities concurrency and relationships And save changes towards the DB

bull EntityClient Data Provider bull 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

bull Data Providers bull This is the lowest layer which translates L2E queries via command tree to native

SQL expression and executes it against the specific DBMS system

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 6: Entity Framework

EF Architecture

6 04102013 Entity Framework Training

copy2013 MSDN

EF Architecture

7 04102013 Entity Framework Training

bull Object Services bull This is where the DBContext is which represents the session of interaction between

the applications and the data source It provides the facilities for tracking changes and managing identities concurrency and relationships And save changes towards the DB

bull EntityClient Data Provider bull 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

bull Data Providers bull This is the lowest layer which translates L2E queries via command tree to native

SQL expression and executes it against the specific DBMS system

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 7: Entity Framework

EF Architecture

7 04102013 Entity Framework Training

bull Object Services bull This is where the DBContext is which represents the session of interaction between

the applications and the data source It provides the facilities for tracking changes and managing identities concurrency and relationships And save changes towards the DB

bull EntityClient Data Provider bull 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

bull Data Providers bull This is the lowest layer which translates L2E queries via command tree to native

SQL expression and executes it against the specific DBMS system

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 8: Entity Framework

DB First Model First The simplistic view

8 04102013 Entity Framework Training

copy2013 Web Camps Team

It seems like thatrsquos a 1 to 1 relationship between DB model and EDM that theyrsquore tied together but itrsquos not Itrsquos not even mandatory to have your DB generated based on your Entity Data Model they could be different and live their own life this is what mapping is for

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 9: Entity Framework

DB model VS Conceptual model

bull A DB model is designed to address storage problems Itrsquos also optimized to deal with performance while fetching data

bull A Business object model is designed to handle business needs

bull They should not look like each other

bull Entity Framework allow you to do so Whatever approach yoursquoll choose yoursquoll be able to isolate both models and handle the mapping wellhellip in the mapping layer -)

9 04102013 Entity Framework Training

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 10: Entity Framework

DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Joseacute A Blakeley answer that question ldquoDo we still have an impedance mismatch problem ldquo

To conclude Irsquod like to quote that comment I found on an article about impedance mismatch that somehow summarizes some useless debates

ldquoRDBMS has its advantages OOP has its advantages and SOA also has its advantages These things arent just useless extra layers theyre tools which all serve different purposes (RDBMS for working with large datasets SOA for implementing complicated business rules OOP for writing more type-safe and maintainable code)

If you stop viewing these concepts as being at war with each other and start viewing them as different perspectives of the same solution all the long-winded arguments about OOP and ORM and whatever start to look a lot more like lame excuses for ordinary human inertia (ie the overwhelming urge to keep doing things the way youre doing them now at any cost)rdquo -)

10 04102013 Entity Framework Training

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 11: Entity Framework

The (in)famous EDMX An EDMX file is just an XML file

Just give that a try Right-click on one EDMX file in Visual Studio and choose ldquoOpen withhelliprdquo menu option and select the XML entry as follows

11 04102013 Entity Framework Training

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 12: Entity Framework

The (in)famous EDMX As I said EDMX is just an XML file

12 04102013

An EDMX is a combination of 3 different parts that make up the whole thing

bull ltedmxStorageModelsgt aka the SSDL

bull ltedmxConceptualModelsgt aka the CSDL

bull ltedmxMappingsgt aka the MSL

hellipyou can even edit those sections manually but at your own risk -)

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 13: Entity Framework

The (in)famous EDMX

13 04102013

By default the EDMX is embedded in the project assembly it belongs to

The connection string will look like this

Entity Framework Training

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 14: Entity Framework

The (in)famous EDMX

14

Itrsquos also possible to generate CSDL SSDL amp MSL by changing the Meta Artifact Processing property of your model to Copy to Output Directory

3 separate XML files

Yes it can be useful in some particular caseshellip

The connection string will look like as right below did you notice the changes

Last piece of advice if you want to edit the XML files by yourself checkout the cookbook first -)

Entity Framework Training

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 15: Entity Framework

The (in)famous EDMX

15 04102013

You might want to have a look at the Edmgen2 tool

As written on the Edmgen2 homepage

EdmGen2 is a command-line tool for the Microsoft ADONET Entity Framework

EdmGenexe can only read and write the CSDL SSDL amp MSL file formats However EdmGen2exe can read and write the EDMX file format used by the Visual Studio design tools

Additionally EdmGen2exe contains some experimental functionality not found in EdmGenexe [hellip] with the ability to identify inheritance relationships in relational database schema [hellip] and constructs a suitable model and mapping

To be complete have a look at this article to see the changes that were made to the EDMX schema since V1 specifications to the current V3

Entity Framework Training

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 16: Entity Framework

The (in)famous EDMX

16 04102013

The goal of this training is not to learn how to manipulate the Entity Data Model Designer in Visual Studio you certainly all know at least the basic features

If you need to go into further details have a look a this MSDN Library article called ldquoModeling and Mapping with Entity Framework Designerrdquo It contains everything yoursquoll need to be able to map CSDL with SSDL like a chef

By the way now you should understand easily why the CSDL is not always updated even if you perform an ldquoUpdate Model From DB Wizardrdquo towards the EDMX It will work only in case of new things added in the DB model As I said CSDL and SSDL must live their own life Entity Framework cannot decide for you whether it needs to remove an entity property if one column has been altereddeleted in the DB Every modification made in your DB schema should impact your MSL rather than your CSDL

Entity Framework Training

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 17: Entity Framework

The (in)famous EDMX

17 04102013

bull Table-per-concrete class mapping

bull Unmapped abstract types When you create an abstract entity type with the Entity Designer the type must be mapped to a table or view

bull Creating conditions on association mappings

bull Mapping associations directly to stored procedures Mapping many-to-many associations is not supported

bull Creating conditions on Function Import mappings

bull Annotations

bull Query views

bull Models that contain references to other models

bull Creating associations without corresponding navigation properties

bull Adding or editing storage model objects (Deleting storage model objects is supported)

bull Adding editing or deleting functions that are defined in the conceptual model

One thing you should know about the Entity Designer is that it has some limitationshellip

But things are getting better have a look at the J Lerman article about the new Entity Designer in VS2012 more to come with VS2013 and EF6 stay tuned

Entity Framework Training

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 18: Entity Framework

Inheritance

18 04102013

Before going further and see what Code First is all about letrsquos talk about table inheritance

Like with classes in OOP in a conceptual model you can define an entity type (a derived type) that inherits from another entity type (the base type) However unlike classes in object-oriented programming in a conceptual model the derived type always inherits all the properties and navigation properties of the base type You cannot override inherited properties in a derived type copy MSDN

There are three main Inheritance Mapping strategies

bull Table Per Hierarchy (TPH)

bull Table Per Type (TPT)

bull Table Per Concrete Class (TPC)

They have all their pros amp cons and it will be up to you to choose the right one

Entity Framework Training

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 19: Entity Framework

Inheritance

19 04102013

Letrsquos see how those mapping strategies work with the simple example from the AdoNet Blog

The entities

Entity Framework Training

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 20: Entity Framework

Inheritance

20 04102013

Table Per Hierarchy (TPH)

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

The table contains a column which I have named lsquoTypersquo This column acts as the discriminator which helps determine the whether a bike is a TTBike or a MountainBike

Entity Framework Training

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 21: Entity Framework

Inheritance

21 04102013

Table Per Type (TPT)

In TPT there is a base table which stores all of the common information There is also one or more derived entities which store the attributes that are unique to that derived entity

The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables

Entity Framework Training

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 22: Entity Framework

Inheritance

22 04102013

Table Per Concrete Class (TPC)

Table per Concrete class creates a table for each derived (or concrete) entity and does not create a table for the base abstract entity

TPC is supported by the Entity Framework at runtime but are not supported by the EF Designer If you want to use TPC you have two options use Code First or manually edit the EDMX file

Entity Framework Training

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 23: Entity Framework

Inheritance

23 04102013

If you have a conceptual model with object inheritance use the OfTypeltTResultTypegt to limit the query to only result of a specific type

Entity Framework Training

foreach (var course in departmentCoursesOfTypeltOnlineCoursegt())

ConsoleWriteLine( Online - 0 courseTitle)

Anyway before going on and implementing one of those inheritance mapping strategies ask your DBA first -)

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 24: Entity Framework

Mapping

24 04102013

We just saw that it was kinda easy to map a DB model with an Object model that are different (and should stay different)

And itrsquos even easier with Code First Code Second approaches But wersquoll see that just after

But therersquos one important thing to mention We all agree that DB model should not drive the way we design our Object model But it should neither be the case the other way round

If you modified your Object model donrsquot take the T-SQL scripts EF will generate to update your DB accordingly for granted

Ask your DBA if itrsquos ok or not before validating any changes in the DB schema

They know better than EF -)

Entity Framework Training

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 25: Entity Framework

Code First Code Second

25 04102013

Code First approach lets you define your conceptual model and mapping to the DB model using code only With Code First you get rid off the EDMX

Whatrsquos Code Second

Itrsquos pretty much the same it means only that you can do it with an existing DB

How

Using the EF Power Tools and use the Reverse Engineer Code First option

By the way EF Power Tools offers other great features

bull Reverse Engineer Code First

bull Customize Reverse Engineer Templates

bull View Entity Data Model(Read-only) XML DDL SQL

bull Generate (pre-compiled) views

Entity Framework Training

Easy

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 26: Entity Framework

Code First Code Second

26 04102013

Letrsquos see how Code First workshellip

Create your classes

public class Blog

public int BlogId get set

public string Name get set

public virtual ListltPostgt Posts get set

public class Post

public int PostId get set

public string Title get set

public string Content get set

public int BlogId get set

public virtual Blog Blog get set

Entity Framework Training

Create your context

public class BloggingContext DbContext

public DbSetltBloggt Blogs get set

public DbSetltPostgt Posts get set

Yeah itrsquos that easy

By convention DbContext has created a database for you

Store data

using (var db = new BloggingContext())

var blog = new Blog Name = laquo MyBlog raquo

dbBlogsAdd(blog)

dbSaveChanges()

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 27: Entity Framework

Code First Code Second - Conventions

27 04102013

EF was able to create a DB based on the model because it uses conventions

bull Primary Key Convention bull If a property on a class is named ldquoIDrdquo or ltclassNamegtID

public int DepartmentID get set

bull Type Discovery bull Your context exposes DbSet properties for the types that you want to be part of the model Code

First will include these types and also will pull in any referenced types even if the referenced types are defined in a different assembly

bull If your types participate in an inheritance hierarchy it is enough to define a DbSet property for the base class and the derived types will be automatically included if they are in the same assembly as the base class

bull Complex Types Convention bull If no primary key can be inferred then the type is automatically registered as a complex type

Entity Framework Training

OVER

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 28: Entity Framework

Code First Code Second - Conventions

28 04102013

bull Relationship Convention bull Any property with the same data type as the primary key and with a name like

bull ltnavigation property namegtltprincipal primary key property namegt

bull ltprincipal class namegtltprimary key property namegt

bull ltprincipal primary key property namegt

will represent a Foreign Key public class Department

Primary key

public int DepartmentID get set

public string Name get set

Navigation property

public virtual ICollectionltCoursegt Courses get set

public class Course

Primary key

public int CourseID get set

public string Title get set

Foreign key

public int DepartmentID get set

Navigation properties

public virtual Department Department get set

bull Code First infers the multiplicity of the relationship based on the nullability of the foreign key

bull If a foreign key on the dependent entity is not nullable then Code First sets cascade delete

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 29: Entity Framework

Code First Code Second - Conventions

29 04102013

bull Connection String Convention bull DbContext uses the namespace qualified name of your derived context class as the database

name and creates a connection string for this database using either SQL Express or LocalDb

bull Removing Conventions bull You can tell EF not to use some conventions like this modelBuilderConventionsRemoveltPluralizingTableNameConventiongt()

bull Pluggable Conventions (EF6) bull Build your own ones

Entity Framework Training

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 30: Entity Framework

Code First Code Second - Annotations

30 04102013

If your classes do not follow any kind of EF conventions you can use attributes called DataAnnotations

One of the coolest thing about DataAnnotations is that itrsquos shared between other frameworks like ASP Net MVC

If you set as property as required

[Required]

public string Title get set

The DB column will be set as ldquonot nullrdquo and the MVC application will perform client side validation even dynamically building a message using the property and annotation names

Entity Framework Training

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 31: Entity Framework

Code First Code Second - Annotations

31 04102013

Herersquos the list of the most common DataAnnotations

bull Key Primary key

bull Required Not null

bull MaxLength and MinLength Obvious -)

bull NotMapped Not need to be stored

bull ComplexType Entity without primary key

bull ConcurrencyCheck If someone has modified the data in the meantime it will fail and throw a DbUpdateConcurrencyException

bull TimeStamp Concurrency based on Timestamp

bull Table and Column change the name of the tables and columns

bull DatabaseGenerated computed properties

bull InverseProperty and ForeignKey Relationship attributes

For relationships go there

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 32: Entity Framework

Code First Code Second ndash Fluent API

32 04102013

We saw that Code First allows you to work with Conventions (over configuration) but this approach will obviously fit only small projects or POCs

DataAnnotations is pushing the mapping capabilities a step forward but keep in mind that it has limitations as well herersquos a non exhaustive list of what it cannot do

bull The precision of a DateTime property bull The precision and scale of numeric properties bull A String or Binary property as fixed-length bull A String property as non-unicode bull The on-delete behavior of relationships bull Advanced mapping strategies

Here comes the Fluent API (here amp here)

The DataAnnotations only cover a subset of the fluent API functionality

Entity Framework Training

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 33: Entity Framework

Code First Code Second ndash Fluent API

33 04102013

The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 34: Entity Framework

Code First Code Second ndash Fluent API

34 04102013

Each Builder can define their mappings

Entity Framework Training

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 35: Entity Framework

Code First Code Second ndash Fluent API

35 04102013

Doing that way you can easily separate your mapping files from your model

The code becomes clearer and no reference is made to any EF libraries when yoursquore designed your business model Which is not possible with DataAnnotations

There are so many options that the Fluent API offers that it would take hours to describe them

Please go and read those 2 articles to go further in details with the Fluent API

bull ConfiguringMapping Properties and Types with the Fluent API

bull Configuring Relationships with the Fluent API

Entity Framework Training

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 36: Entity Framework

Code First ndash Migrations

36 04102013

A word on Code First Migrations

Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code Itrsquos based on Active Record migrations (the primary data access technology used by the Rails framework)

Itrsquos an easy way to be able to generate the scripts needed to go from one version of your DB model to the V+1 or to be able to downgrade a schema version as well

I wonrsquot go any further but as itrsquos a really nice feature go and see more details on MSDN

Entity Framework Training

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 37: Entity Framework

Eager Lazy amp Explicit Loading

37 04102013

Entity Framework allows you fetch for data and load their relationships in many ways

3 of them are

bull Eager Loading

bull Lazy Loading

bull Explicit Loading

Once again all of them have their pros amp cons and should be used with attention

What is the best choice between multiple requests against the database versus a single request that may contain a large payload It may be appropriate to use eager loading in some parts of your application and lazy loading in other parts

Wersquoll try to see thathellip

Entity Framework Training

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 38: Entity Framework

Eager Lazy amp Explicit Loading

38 04102013

Letrsquos have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN

Seems that it wonrsquot be a good option for our sites to switch on Lazy loading

Entity Framework Training

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 39: Entity Framework

Eager Lazy amp Explicit Loading

39 04102013

One good option seems to load exactly what we need

But this can be done in several ways as well

While including related entities in a query is powerful its important to understand whats happening under the covers Letrsquos look how the Include() workshellip

As stated on MSDN

It takes a relatively long time for a query with multiple Include statements in it to go through our internal plan compiler to produce the store command The majority of this time is spent trying to optimize the resulting query The generated store command will contain an Outer Join or Union for each Include depending on your mapping Queries like this will bring in large connected graphs from your database in a single payload which will acerbate any bandwidth issues especially when there is a lot of redundancy in the payload (ie with multiple levels of Include to traverse associations in the one-to-many direction) CustomersInclude(c =gt cOrders) (click if you dare)

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 40: Entity Framework

Eager Lazy amp Explicit Loading

40 04102013

SELECT [Project1][C1] AS [C1] [Project1][CustomerID] AS [CustomerID] [Project1][CompanyName] AS [CompanyName] [Project1][ContactName] AS [ContactName] [Project1][ContactTitle] AS [ContactTitle] [Project1][Address] AS [Address] [Project1][City] AS [City] [Project1][Region] AS [Region] [Project1][PostalCode] AS [PostalCode] [Project1][Country] AS [Country] [Project1][Phone] AS [Phone] [Project1][Fax] AS [Fax] [Project1][C2] AS [C2] [Project1][OrderID] AS [OrderID] [Project1][CustomerID1] AS [CustomerID1] [Project1][EmployeeID] AS [EmployeeID] [Project1][OrderDate] AS [OrderDate] [Project1][RequiredDate] AS [RequiredDate] [Project1][ShippedDate] AS [ShippedDate] [Project1][ShipVia] AS [ShipVia] [Project1][Freight] AS [Freight] [Project1][ShipName] AS [ShipName] [Project1][ShipAddress] AS [ShipAddress] [Project1][ShipCity] AS [ShipCity] [Project1][ShipRegion] AS [ShipRegion] [Project1][ShipPostalCode] AS [ShipPostalCode] [Project1][ShipCountry] AS [ShipCountry] FROM ( SELECT [Extent1][CustomerID] AS [CustomerID] [Extent1][CompanyName] AS [CompanyName] [Extent1][ContactName] AS [ContactName] [Extent1][ContactTitle] AS [ContactTitle] [Extent1][Address] AS [Address] [Extent1][City] AS [City] [Extent1][Region] AS [Region] [Extent1][PostalCode] AS [PostalCode] [Extent1][Country] AS [Country] [Extent1][Phone] AS [Phone] [Extent1][Fax] AS [Fax] 1 AS [C1] [Extent2][OrderID] AS [OrderID] [Extent2][CustomerID] AS [CustomerID1] [Extent2][EmployeeID] AS [EmployeeID] [Extent2][OrderDate] AS [OrderDate] [Extent2][RequiredDate] AS [RequiredDate] [Extent2][ShippedDate] AS [ShippedDate] [Extent2][ShipVia] AS [ShipVia] [Extent2][Freight] AS [Freight] [Extent2][ShipName] AS [ShipName] [Extent2][ShipAddress] AS [ShipAddress] [Extent2][ShipCity] AS [ShipCity] [Extent2][ShipRegion] AS [ShipRegion] [Extent2][ShipPostalCode] AS [ShipPostalCode] [Extent2][ShipCountry] AS [ShipCountry] CASE WHEN ([Extent2][OrderID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2] FROM [dbo][Customers] AS [Extent1] LEFT OUTER JOIN [dbo][Orders] AS [Extent2] ON [Extent1][CustomerID] = [Extent2][CustomerID] WHERE NUK = [Extent1][Country] ) AS [Project1] ORDER BY [Project1][CustomerID] ASC [Project1][C2] ASC

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 41: Entity Framework

Eager Lazy amp Explicit Loading

41 04102013

Well well wellhellip what are the options then

bull Try to reduce the number of Include statements in your query to just bring in the data you need

bull Break your query into a smaller sequence of subqueries

Rather than that Do that

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 42: Entity Framework

Eager Lazy amp Explicit Loading

42 04102013

And what is Explicit Loading exactly

Even with lazy loading disabled it is still possible to lazily load related entities but it must be done with an explicit call To do so you use the Load method on the related entityrsquos entry

var blog = contextBlogsFind(1)

Load the posts related to a given blog

contextEntry(blog)Collection(p =gt pPosts)Load()

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities

Load the posts with the entity-framework tag related to a given blog

contextEntry(blog)

Collection(b =gt bPosts)

Query()

Where(p =gt pTagsContains(entity-framework)

Load()

Entity Framework Training

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 43: Entity Framework

Eager Lazy amp Explicit Loading

43 04102013

Wanna be the king of loading entities

Go there

Entity Framework Training

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 44: Entity Framework

Performance Profiling

44 04102013

ORMrsquos are often considered by DBArsquos as the evil

One of their fears if the T-SQL generated by Entity Framework We have seen that in some examples we can only give them reason

The T-SQL can be ugly and lead to really poor performance

Here comes the profiling

Therersquos a lot of tools that allow you to do so Please read this article from Julie Lerman where she explains how to perform profiling (see the comments as well)

Once again do not hesitate to talk to your DBA for any kind of advice

Entity Framework Training

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 45: Entity Framework

Performance Profiling

45

There are also a lot of best practice when itrsquos time to solve performance issues

Herersquos an non exhaustive list of what can be done

bull Cold vs Warm Query Execution

bull (mapping) View generation

bull Moving your model to a separate assembly

bull Caching (objects results query plans amp metadata)

bull Complied amp Auto-compiled queries

bull NoTracking queries

bull Inhetirance strategies

bull Upgrade to EF5 -)

bull Lazy vs Eager

bull hellip

Go here amp here amp here for much more details

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 46: Entity Framework

Appendix

46 04102013

ADO Net Blog

Julie Lermanrsquos Blog Rowan Millerrsquos Blog Arthur Vickerrsquos Blog Alex Jamersquos Blog

T4 Templates and the Entity Framework

Effort - Entity Framework Unit Testing Tool

Whatrsquos Best for Unit Testing in EF It depends dude

Creating an Entity Framework Data Model for an ASPNET MVC Application (1 of 10)

AddAttach and Entity States

Table-Valued Functions (TVFs)

Extending And Customizing Code First Models ndash Part 1 Of 2

Code First InsertUpdateDelete Stored Procedure Mapping (EF6)

Me and Entity Framework on StackOverflow

Entity Framework Training

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 47: Entity Framework

Find out more

bull On httpstechblogbetclicgroupcom

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players

Page 48: Entity Framework

About Betclic bull Betclic Everest Group one of the world leaders in online gaming has a unique portfolio

comprising various complementary international brands Betclic Everest Gaming bet-at-homecom Expekthellip

bull Active in 100 countries with more than 12 million customers worldwide the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association)

bull Through our brands Betclic Everest Group places expertise technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players