Entity Framework v2 Best Practices


Published on

Entity Framework v2 in .NET 4.0. Some intro and best Practices.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Dr. Edgar F. CoddE. F. Codd (Edgar F. "Ted" Codd) formed the concepts for organizing and accessing data that are embodied in the relational database, the predominant approach to data organization in today's business world. Critical of IBM's then current data management systems, Codd, as a young IBM programmer working in IBM's San Jose Research Lab in California in 1970, proposed that data be organized according to principles based on identified relations between various kinds of data. The data itself would be organized in two-dimensional (row and column) tables and specific items in a table could be related to data located in other tables. Codd saw the need to reduce or eliminate redundancy in data and to allow data to be accessed through logical rather than physical identification. One of Codd's key ideas was the process for organizing data into the appropriate number of tables, a process known asnormalization.
  • - No separation between code and database schema. You still see a lot of SQL statements.- You also create dependency with specific database schema- SAP ERP database contains more than 30,000 tables.
  • Maintainabity, security, efficiency andscalability let a DBA decideto:Splitdata of oneentityintoseveraltablesPutting data forseveral types of entitiesintosametableSupply projectionsthatlooseentity concepts thatmight have been present in tablestructures
  • Typed Datasets – shippedObjectspaces ‘v1’ – never shippedObjectspaces ‘v2’ – never shippedMicrosoft Business Framework – never shippedWinFS – never shippedLinq to SQL – shipped, won’t be discontinuedLinq to Entities – shippedEntity Framework- shipped 
  • Entity Framework- shipped 
  • ERM = Entity-Relationship ModelEDM = Entity Data Model
  • Explain the inner workings of the entity framework Three types of commands: LINQ to Entities against Object Services Materialization to Conceptual model classes or anonymous classes if projected Entity Sqlagaints Object Services Materialization if no projection + streamed data on row level Call model defines functions or specific Entity SQL functions. Entity Sql against Entity Client No materialization + streamed data on column levelExplain the path of commands…
  • Do I need an Entity Data Model before I can use POCO?Yes – POCO support in Entity Framework 4.0 simply removes the need of having persistence specific concerns in your entity classes. There is still the need for you to have a CSDL/SSDL/MSL (collectively EDMX) metadata so that the Entity Framework is able to use your entities along with the metadata in order to enable data access. There is a separate effort that we are working on that will allow you to do true “code-first” development without the need to have a predefined EDMX model. A community preview of this feature will be released to the web in the coming months. We will roll this into the product the first chance we get. As always, your feedback will be helpful.How is metadata mapped when using POCO entities?In Entity Framework 3.5, both EntityObject and IPOCO based entities relied on the use of mapping attributes that were meant for decorating and mapping the entity types and properties back to the corresponding elements in the Conceptual model. Entity Framework 4.0 introduces convention based mapping for allowing mapping of Entity Types, Properties, Complex Types and Relationships back to the conceptual model without the need for explicit decoration. The simple rule here is that Entity Type names, Property names and Complex Types names used in your POCO classes must match those defined by the conceptual model. Namespace names are ignored and don’t have to match between the class definition and the conceptual model.Is Deferred (Lazy) Loading supported with POCO?Yes – Deferred (Lazy) loading is supported with POCO through the use of proxy types that are used to provide automatic lazy loading behavior on top of your POCO classes. This is something that we’ll cover when we get to deferred loading – until then know that eager loading via the use of “Include” is also supported, like so:
  • The virtual keyword is used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class. When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.What’s going on under the covers?The reason why this works is because when I marked my collection property as virtual, this allowed the Entity Framework to provide a proxy instance for my POCO type at runtime, and it is this proxy that does automatic deferred loading. The proxy instance is based on a type that derives from my own POCO entity class - so all functionality you have provided is preserved. From a developer point of view, this allows you to write persistence ignorant code even when deferred loading might be a requirement.Manual instantiation of Proxy instances for POCO entitiesIn order to enable creation of proxy instances for adding/attaching, you can use the CreateObject factory method on ObjectContext for creating entity instances:Category category = context.CreateObject<Category>();
  • Snapshot based change tracking is what you get with pure POCO entities that don’t use proxies to handle change tracking. This is a simple change tracking solution that relies on complete snapshots of before and after values being maintained by the Entity Framework. These values are compared during SaveChanges to determine what has truly changed from their original values. In this model, unless you are using Lazy loading (must use virtual keyword), the runtime type of your entities is the same as you define for your POCO entities.Problem:Entity Framework’s Object State manager will go out of sync with your own object graph, before SaveChanges called. That’s because of no direct notification of changes to EF anytime your objects changeThecomparison during SaveChangesis relatively expensive when compared to the way change tracking works with EntityObject (non POCO) based entities.Proxy based Change Tracking is a different solution if you care about very efficient and up to date change tracking as you make changes to your entity values, relationships and object graph.You can leverage proxy based change tracking for a particular entity type if you declare all mapped properties on that entity type as virtual.Change Tracking proxies subclass your POCO entity class to provide you with this capability during runtime without requiring you to implement the IPOCO interfaces yourself.How?Your class must be public, non-abstract or non-sealed. Your class must also implement public virtual getters/setters for all properties that are persisted/mapped. Finally, you must declare collection based relationship navigation properties as ICollection<T> only. They cannot be a concrete implementation or another interface that derives from ICollection<T> (a difference from the Deferred Loading proxy)
  • http://www.robbagby.com/entity-framework/is-lazy-loading-in-ef-4-evil-or-the-second-coming/
  • T4 = Text Template Transformation Toolkit
  • Entity Framework v2 Best Practices

    1. 1. Entity framework v2Best Practices<br />Microsoft Innovation Day 2010, May 11, 2010<br />AndriYadi| a@dycode.com<br />CEO, DyCode | MVP, VSTO<br />
    2. 2. http://itunes.com/apps/movreak<br />
    3. 3. JSON<br />WCF Data Services<br />HTTP/REST<br />Entity Framework<br />Real-world Scenario<br />SQL Server 2008<br />
    4. 4. Dr. EF. Codd<br />
    5. 5.
    6. 6. INSERT<br />UPDATE<br />SELECT<br />DELETE<br />WHERE<br />HAVING<br />ORDER BY<br />Then we code in SQL<br />RIGHT<br />JOIN<br />COUNT<br />UNION<br />MIN/MAX<br />LEFT<br />
    7. 7. ADO.NET code<br />SqlCommandoCmd;<br />SqlDataReaderoDR;<br />string connString = ConfigurationManager.<br />ConnectionStrings["OracleConnString"].<br />ConnectionString;<br />SqlConnectionconn = new SqlConnection(connString);<br />string selectQuery;<br />int _returnValue = 0;<br />selectQuery= “SELECT COUNT(OrderID) from Orders“ + “where EmployeeID=@EmpID”;<br />conn.Open();<br />oCmd= new SqlCommand(selectQuery, conn);<br />oCmd.Parameters.Add(“@EmpID”, SqlDbType.Int);<br />oCmd.Parameters[“@EmpID”].Value = employeeID;<br />oDR= oCmd.ExecuteReader();<br />if (oDR.Read())<br /> _returnValue = oDR.GetInt32(0);<br />oDR.Close();<br />conn.Close();<br />
    8. 8. The Dilemma<br />Software Architects & Developers<br />Database Designers & Administrators<br />
    9. 9. ADO.NET <br />ADO<br />(1996)<br />DAO<br />(1992)<br />RDO<br />
    10. 10. Enough! We need ORM!<br />
    11. 11. Object Relational Mapping<br />Technique for working with relational tables as if they were objects in memory<br />Hide away the complexity of the underlying tables and give a uniform way of working with data<br />
    12. 12. Why ORM?<br />Development productivity<br />Database independence<br />Database portability<br />
    13. 13. Many attempts<br />Typed Datasets<br />Objectspaces ‘v1’<br />Objectspaces ‘v2’<br />Microsoft Business Framework<br />WinFS<br />Linq to SQL<br />NHibernate<br /> Will “RIP”<br /> Not Microsoft’s<br />
    14. 14. ADO.NET Entity Framework<br />Microsoft’s strategic technology<br />Used in other Microsoft technologies (reporting services)<br />V2 released with .NET 4.0<br />14<br />
    15. 15. Entity Data Model<br />Invented in the 1970s, by Dr. Peter Chen<br />ERM<br />Conceptual Layer<br />Mapping Layer<br />Storage Layer<br />Now: EDM in ADO.NET Entity Framework<br />
    16. 16. Entity Framework vsLinqToSQL<br />
    17. 17. Let’s go deeper on EF2<br />
    18. 18. IEnumerable<T><br />LINQ to Entities<br />Entity SQL Query<br />Entity Framework<br />EDM<br />EntityDataReader<br />Command Tree<br />Entity SQL Query<br />Conceptual Model<br />Mapping<br />Entity Framework<br />EntityDataReader<br />Command Tree<br />Storage Model<br />Entity Framework<br />
    19. 19. Demo<br />Model-first<br />
    20. 20. Eager Loading<br />Structure the initial query in such a way that all of the required objects are returned in the initial query<br />from c in nw.Customers.Include("Orders")select c; <br />
    21. 21. Explicit Loading<br />Explicitly request to load the related objects<br />customer.Orders.Load(); <br />
    22. 22. Lazy Loading<br />Related objects are loaded automatically for you when you access them<br />
    23. 23. POCO Support<br />Plain Old CLR Object<br />User your own POCO objects with no EF attributes<br />Code your POCO classes<br />Code Entity Framework Context<br />Or use T4 POCO entity generator by VS2010<br />
    24. 24. Questions on POCO<br />Do I still need an EDM? Yes<br />How is metadata mapped to POCO entities? Convention based mapping<br />Entity Type, Property, and Complex Types names must match those defined by in EDM<br />Is deferred/lazy loading supported? Yes<br />
    25. 25. Lazy Loading on POCO<br />Declare lazy-loaded property as virtual<br />Make sure to enable ContextOptions.LazyLoadingEnabled<br />What’s under the hood?<br />
    26. 26. POCO Change tracking<br />Snapshot-based<br />Proxy-based<br />
    27. 27. Demo<br />POCO<br />
    28. 28. Demo<br />Generate EDM from database<br />
    29. 29. Performance & security?<br />Connections to database vs. amount of data<br />You can work with stored procedures <br />You can work with views<br />You can define how the ADO.NET Entity Framework loads your data to <br />Eager <br />Lazy<br />(Explicit)<br />
    30. 30. EF v2 in Distributed System<br />
    31. 31. A WCF Service<br />Proxy<br />Data Binding<br />Entity Framework<br />ObjectContext available<br />ObjectContext not available<br />Distributed system – WCF service<br />SQL Server 2008<br />
    32. 32. JSON/<br />XML<br />HTTP/REST<br />WCF Data Service<br />DataServiceContext<br />Data Binding<br />HTTP/REST<br />Entity Framework<br />ObjectContext available<br />ObjectContext not available<br />Distributed system – WCF Data service<br />SQL Server 2008<br />
    33. 33. So, WHAT’s NEW in EF2?<br />
    34. 34. Entity enhancements<br />Foreign-keys supported in the conceptual model<br />Testability enhancements<br />IObjectSet<T> and ObjectSet<T><br />Easier to mock data context and data entities for tests<br />Lazy loading for related objects<br />Options now for explicit or implicit loading<br />
    35. 35. Support for persistence ignorant objects<br />Persistence ignorant objects<br />POCO objects with no EF attributes, etc.<br />Mapped to conceptual model via convention<br />Change tracking possible with generated proxies or snapshot<br />Managing types in n-tier applications<br />Easier to add/attach objects to a context<br />More control over object state<br />Issues you should consider<br />You still need the Entity Data Model (edmx)<br />To use objects with WCF – use ProxyDataContractResolver<br />
    36. 36. Designer enhancements<br />Support for complex types<br />Singularization& pluralization<br />Model first development<br />Creates DDL for database based on your model<br />Designer extensibility <br />Influence the EDMX generation<br />Add visuals<br />Influence DDL creation<br />
    37. 37. Code generation customization<br />Based on T4 templates<br />Included as of VS 2008<br />Runtime support, but not much design support<br />T4 and Entity Framework <br />T4 used to generate code from model<br />Create new T4 templates to use instead<br />Add validation logic<br />Create POCO objects<br />
    38. 38. References<br />ADO.NET team blog – keep up with new features in Entity framework<br />http://blogs.msdn.com/adonet<br />ADO.NET C# POCO Entity Generator <br />ADO.NET C# Web Site POCO Entity Generator <br />WCF Data Services team blog<br />http://blogs.msdn.com/astoriateam<br />
    39. 39. DyCode<br />www.dycode.com | office@dycode.com<br />Dynamic IT Solutions for Optimal Business Value<br />