entity framework

of 48/48
Entity Framework Training

Post on 10-May-2015




2 download

Embed Size (px)


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.


  • 1.Entity Framework Training

2. Agenda A brief history Whats an ORM? Entity Framework Architecture DB First / Model First and the (in)famous EDMX Inheritance Code First / Code Second Eager / Lazy & Explicit Loading Performance / Profiling 204/10/2013 Entity Framework Training 3. A brief history EF releases and versioning is a bit of a mess :-) EF aka EF1 aka EF 3.5 was released with . NET 3.5 (VS2008) Basic ORM functionalities / DB first only EF 4 was released with . NET 4.0 (VS2010) POCO support / Lazy loading EF 4.1 DBContext API / Code First / Nuget package EF 4.1.1 and then EF 4.2 Mainly bug fixes EF 4.3 Code First Migration EF 4.3.1 Bug fixes / better LocalDB support 304/10/2013 Entity Framework Training 4. A brief history MS guys were the first to admit that this versioning was not clear and thats why they rationalize how they were naming and distributing their releases EF 5 This release can be used in Visual Studio 2010 and Visual Studio 2012 to write applications that target .NET 4.0 and .NET 4.5 But when targeting .NET 4.5 you have enum support / table-valued functions / performance improvements / multiple-diagrams per model EF 6 Async Query and Save / Testability improvements / DbSet.AddRange & RemoveRange / DbChangeTracker.HasChanges / Dependency Resolution / Code First Mapping to Insert/Update/Delete Stored Procedures / Have a look at this post on ADO .NET Blog where MS guys were calling for feedback about versioning issues 404/10/2013 Entity Framework Training 5. Whats an ORM? ORM stands for Object-Relational Mapping. According to Wikipedias 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. 504/10/2013 Entity Framework Training 2010 J. Lerman 6. EF Architecture 604/10/2013 Entity Framework Training 2013 MSDN 7. EF Architecture 704/10/2013 Entity Framework Training Object Services 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. EntityClient Data Provider This provider manages connections, translates entity queries into data source- specific queries, and returns a data reader that the Entity Framework uses to materialize entity data into objects. Data Providers This is the lowest layer which translates L2E queries via command tree to native SQL expression and executes it against the specific DBMS system 8. DB First / Model First The simplistic view: 804/10/2013 Entity Framework Training 2013 Web Camps Team It seems like thats a 1 to 1 relationship between DB model and EDM, that theyre tied together, but its not. Its 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! 9. DB model VS Conceptual model A DB model is designed to address storage problems. Its also optimized to deal with performance while fetching data. A Business object model is designed to handle business needs. They should not look like each other! Entity Framework allow you to do so. Whatever approach youll choose, youll be able to isolate both models and handle the mapping, well in the mapping layer ;-) 904/10/2013 Entity Framework Training 10. DB model VS Conceptual model Please read this pretty interesting article where Rowan Miller and Jos A. Blakeley answer that question: Do we still have an impedance mismatch problem? To conclude, Id like to quote that comment I found on an article about impedance mismatch, that somehow summarizes some useless debates: RDBMS has its advantages, OOP has its advantages, and SOA also has its advantages. These things aren't just useless extra "layers", they're 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 (i.e. the overwhelming urge to keep doing things the way you're doing them now, at any cost). ;-) 1004/10/2013 Entity Framework Training 11. 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 Open with menu option and select the XML entry as follows: 1104/10/2013 Entity Framework Training 12. The (in)famous EDMX As I said, EDMX is just an XML file: 1204/10/2013 An EDMX is a combination of 3 different parts that make up the whole thing: aka the SSDL aka the CSDL aka the MSL you can even edit those sections manually, but at your own risk! :-) 13. The (in)famous EDMX 1304/10/2013 By default, the EDMX is embedded in the project assembly it belongs to: The connection string will look like this: Entity Framework Training 14. The (in)famous EDMX 14 Its also possible to generate CSDL, SSDL & 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 cases 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 15. The (in)famous EDMX 1504/10/2013 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 ADO.NET Entity Framework. EdmGen.exe can only read and write the CSDL, SSDL & MSL file formats. However, EdmGen2.exe can read and write the EDMX file format used by the Visual Studio design tools. Additionally, EdmGen2.exe contains some experimental functionality not found in EdmGen.exe. [] with the ability to identify inheritance relationships in relational database schema [] 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 16. The (in)famous EDMX 1604/10/2013 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 Modeling and Mapping with Entity Framework Designer. It contains everything youll 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 Update Model From DB Wizard 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 altered/deleted in the DB. Every modification made in your DB schema should impact your MSL rather than your CSDL. Entity Framework Training 17. The (in)famous EDMX 1704/10/2013 Table-per-concrete class mapping. Unmapped abstract types. When you create an abstract entity type with the Entity Designer, the type must be mapped to a table or view. Creating conditions on association mappings. Mapping associations directly to stored procedures. Mapping many-to-many associations is not supported. Creating conditions on Function Import mappings. Annotations. Query views. Models that contain references to other models. Creating associations without corresponding navigation properties. Adding or editing storage model objects. (Deleting storage model objects is supported.) 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 limitations 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 18. Inheritance 1804/10/2013 Before going further and see what Code First is all about, lets 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. MSDN There are three main Inheritance Mapping strategies: Table Per Hierarchy (TPH) Table Per Type (TPT) Table Per Concrete Class (TPC) They have all their pros & cons and it will be up to you to choose the right one! Entity Framework Training 19. Inheritance 1904/10/2013 Lets see how those mapping strategies work with the simple example from the Ado.Net Blog. The entities: Entity Framework Training 20. Inheritance 2004/10/2013 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 Type. This column acts as the discriminator, which helps determine the whether a bike is a TTBike or a MountainBike. Entity Framework Training 21. Inheritance 2104/10/2013 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 22. Inheritance 2204/10/2013 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 23. Inheritance 2304/10/2013 If you have a conceptual model with object inheritance, use the OfType to limit the query to only result of a specific type. Entity Framework Training foreach (var course in department.Courses.OfType()) { Console.WriteLine(" Online - {0}", course.Title); } Anyway, before going on and implementing one of those inheritance mapping strategies, ask your DBA first! ;-) 24. Mapping 2404/10/2013 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 its even easier with Code First / Code Second approaches! But well see that just after. But theres 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, dont take the T-SQL scripts EF will generate to update your DB accordingly, for granted. Ask your DBA if its ok or not before validating any changes in the DB schema! They know better than EF ;-) Entity Framework Training 25. Code First / Code Second 2504/10/2013 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! Whats Code Second? Its 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: Reverse Engineer Code First Customize Reverse Engineer Templates View Entity Data Model(Read-only) / XML / DDL SQL Generate (pre-compiled) views Entity Framework Training Easy! 26. Code First / Code Second 2604/10/2013 Lets see how Code First works Create your classes: public class Blog { public int BlogId { get; set; } public string Name { get; set; } public virtual List 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 DbSet Blogs { get; set; } public DbSet Posts { get; set; } } Yeah, its that easy! By convention DbContext has created a database for you. Store data using (var db = new BloggingContext()) { var blog = new Blog { Name = MyBlog }; db.Blogs.Add(blog); db.SaveChanges(); } 27. Code First / Code Second - Conventions 2704/10/2013 EF was able to create a DB based on the model because it uses conventions! Primary Key Convention If a property on a class is named ID or ID: public int DepartmentID { get; set; } Type Discovery 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. 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. Complex Types Convention If no primary key can be inferred then the type is automatically registered as a complex type Entity Framework Training OVER 28. Code First / Code Second - Conventions 2804/10/2013 Relationship Convention Any property with the same data type as the primary key and with a name like: will represent a Foreign Key public class Department { // Primary key public int DepartmentID { get; set; } public string Name { get; set; } // Navigation property public virtual ICollection 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; } } Code First infers the multiplicity of the relationship based on the nullability of the foreign key If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete 29. Code First / Code Second - Conventions 2904/10/2013 Connection String Convention 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. Removing Conventions You can tell EF not to use some conventions like this: modelBuilder.Conventions.Remove(); Pluggable Conventions (EF6) Build your own ones! Entity Framework Training 30. Code First / Code Second - Annotations 3004/10/2013 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 its 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 not null and the MVC application will perform client side validation, even dynamically building a message using the property and annotation names. Entity Framework Training 31. Code First / Code Second - Annotations 3104/10/2013 Heres the list of the most common DataAnnotations: Key: Primary key Required: Not null MaxLength and MinLength: Obvious ;-) NotMapped: Not need to be stored ComplexType: Entity without primary key ConcurrencyCheck: If someone has modified the data in the meantime, it will fail and throw a DbUpdateConcurrencyException TimeStamp: Concurrency based on Timestamp Table and Column: change the name of the tables and columns DatabaseGenerated: computed properties InverseProperty and ForeignKey: Relationship attributes For relationships, go there! 32. Code First / Code Second Fluent API 3204/10/2013 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, heres a non exhaustive list of what it cannot do: The precision of a DateTime property The precision and scale of numeric properties A String or Binary property as fixed-length A String property as non-unicode The on-delete behavior of relationships Advanced mapping strategies Here comes the Fluent API! (here & here) The DataAnnotations only cover a subset of the fluent API functionality! Entity Framework Training 33. Code First / Code Second Fluent API 3304/10/2013 The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext. 34. Code First / Code Second Fluent API 3404/10/2013 Each Builder can define their mappings Entity Framework Training 35. Code First / Code Second Fluent API 3504/10/2013 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 youre 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 Configuring/Mapping Properties and Types with the Fluent API Configuring Relationships with the Fluent API Entity Framework Training 36. Code First Migrations 3604/10/2013 A word on Code First Migrations. Entity Framework Code First Migrations enable changes to your model to be propagated to your database through code. Its based on Active Record migrations (the primary data access technology used by the Rails framework). Its 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 wont go any further, but as its a really nice feature, go and see more details on MSDN! Entity Framework Training 37. Eager / Lazy & Explicit Loading 3704/10/2013 Entity Framework allows you fetch for data and load their relationships in many ways. 3 of them are: Eager Loading Lazy Loading Explicit Loading Once again all of them have their pros & 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. Well try to see that Entity Framework Training 38. Eager / Lazy & Explicit Loading 3804/10/2013 Lets have a look at the Lazy Loading versus Eager Loading cheat sheet from MSDN Seems that it wont be a good option for our sites to switch on Lazy loading! Entity Framework Training 39. Eager / Lazy & Explicit Loading 3904/10/2013 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, it's important to understand what's happening under the covers. Lets look how the .Include() works 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 (i.e. with multiple levels of Include to traverse associations in the one-to-many direction). Customers.Include(c => c.Orders) (click if you dare!) 40. Eager / Lazy & Explicit Loading 4004/10/2013 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 N'UK' = [Extent1].[Country] ) AS [Project1] ORDER BY [Project1].[CustomerID] ASC, [Project1].[C2] ASC 41. Eager / Lazy & Explicit Loading 4104/10/2013 Well, well, well what are the options then? Try to reduce the number of Include statements in your query to just bring in the data you need Break your query into a smaller sequence of subqueries Rather than that: Do that: 42. Eager / Lazy & Explicit Loading 4204/10/2013 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 entitys entry. var blog = context.Blogs.Find(1); // Load the posts related to a given blog context.Entry(blog).Collection(p => p.Posts).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 context.Entry(blog) .Collection(b => b.Posts) .Query() .Where(p => p.Tags.Contains("entity-framework") .Load(); Entity Framework Training 43. Eager / Lazy & Explicit Loading 4304/10/2013 Wanna be the king of loading entities? Go there! Entity Framework Training 44. Performance / Profiling 4404/10/2013 ORMs are often considered by DBAs 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! Theres 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 45. Performance / Profiling 45 There are also a lot of best practice when its time to solve performance issues. Heres an non exhaustive list of what can be done: Cold vs. Warm Query Execution (mapping) View generation Moving your model to a separate assembly Caching (objects , results, query plans & metadata) Complied & Auto-compiled queries NoTracking queries Inhetirance strategies Upgrade to EF5 ;-) Lazy vs Eager Go here & here & here for much more details! 46. Appendix 4604/10/2013 ADO .Net Blog Julie Lermans Blog, Rowan Millers Blog, Arthur Vickers Blog, Alex James Blog T4 Templates and the Entity Framework Effort - Entity Framework Unit Testing Tool Whats Best for Unit Testing in EF? It depends, dude! Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10) Add/Attach and Entity States Table-Valued Functions (TVFs) Extending And Customizing Code First Models Part 1 Of 2 Code First Insert/Update/Delete Stored Procedure Mapping (EF6) Me and Entity Framework on StackOverflow Entity Framework Training 47. Find out more On https://techblog.betclicgroup.com/ 48. About Betclic 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- home.com, Expekt 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). 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.