What Impact Will Entity Framework Have On Architecture
1. What impact will the Entity Framework and Entity Data Model have on application architecture? Eric Nelson Microsoft UK Blog: http://geekswithblogs.net/iupdateable Twitter: http://twitter.com/ericnel and http://twitter.com/ukmsdn Podcast: http://bit.ly/msdnpodcast Newsletter: http://msdn.microsoft.com/en-gb/flash Slides, links and background “diary” posts can be found on my blog
2. Agenda ORM Overview and Impact Entity Framework V1 recap Entity Framework V4 overview Impact of embracing Entity Framework
4. Why did the industry create ORMs? We started with data in the 70s The first RDBMS were data centric Overtime they received bolt ons for behaviour In the late 90s, programming became object centric Rise of OOP and OOD Behaviour The two approaches didn’t play nice “impedance mismatch” Different type systems Different emphasis Set vs Graph theory Many to Many
6. The “winning approach” – Object Relational Mapping Technique for working with relational data as if they were objects in memory Hide away the complexity of the underlying tables and give a uniform way of working with data An Abstraction RDBMS is about data OO is about data + behaviour
7. What good comes from adopting an ORM Developer productivity Less code Better code than the “average” developer Better database code than the “average” developer Retain database independence
8. ORM and Code Gen ORMs are highly configurable code gen tools Made normally by someone else We like code gen Helps with DRY But we sometimes dislike ORMs As they can break YAGNI And they often are “leaky” And we didn’t write them And they aren’t perfect for what we have in mind
9. ORM is not... The answer to life the universe and everything The absolute fastest way to do everything Supported by many reporting tools Always in step with RDBMS advances
10. ORM is the Vietnam of Computer Science Ted Neward “there is no good solution to the object/relational mapping problem” Painful tradeoffs Proposed “Integration of relational concepts into the languages”
12. Impact of adopting an ORM Start with Behaviour or start with Data? Code firstor Map first? Database Independence but at what cost? Always access via the ORM? No behaviour in the database?
13. Behaviour in the database? RDBMS can model data and behaviour Stored Procedures Triggers Views User defined types Some RDBMS better than others SQL Server 2005/2008 can run .NET code and you can extend the type system.
14. Stored Procedures are evil? From the world of Java All about portability and vendor neutrality Stored Procedures were hard to port ANSI SQL std doesnt includes SPs Therefore don’t use Stored Procedures This is changing... From the world of .NET Overuse Incorrect use Lead to “no sps here”
15. Stored Procedures and ORMS Some ORMs offer little or no support Some offer great support CUDvs CRUD Functions Still a great choice Can solves identified performance bottlenecks Bulk data manipulation Maintenance operations Multiple applications to the same database Security (hmmm....)
17. ORM on the Windows Platform Many ORMs out there No clear “winner” = relatively little adoption of ORM Developers waiting on Microsoft
18. The future of ORM on Windows Entity Framework and LINQ to Entities is our strategic technology Big investment into Entity Framework 4.0 in VS2010 Best of LINQ to SQL moves into LINQ to Entities Microsoft is using it Data Services - shipping Reporting Services more Partners supporting it Database Vendors – IBM,OpenLink, DataDirect, Devart etc ORM vendors supporting it Entity Framework is not just about ORM
19. ADO.NET Entity Framework Tools and services to create an Entity Data Model (EDM) Tools and services for consuming an Entity Data Model
20. Entity Data Model Entity Data Model Application model Mapped to a persistence store Comprised of three layers: Conceptual (CSDL) Mapping (MSL) Storage (SSDL) Database agnostic Comprised of: Entities Associations Functions Conceptual Mapping Storage
21. Consuming the EDM 1 2 The ORM - optional Object Services 3 Entity Client
23. LINQ recap “Bringing relational into the languages” Eliminating the impedance mismatch (No... Not really ) LINQ to SQL is like C# to C++ Tidy, Composable, Associations, Shaped results, Parameterization, Client processing http://linqpad.net/WhyLINQBeatsSQL.aspx
26. ADO.NET Entity Framework v4.0 And in Visual Studio 2010 and .NET Framework 4.0 we get our fourth release building on the success of 1.0, 2.0 and 3.0
27. Lots of new features Better Tools and Design Experience More powerful/flexible runtime And N-Tier Persistence Ignorance Code Only
28. Better Tools and Design Experience Templated code generation Model First Stored Procedures Pluralization Complex Types Better delete and search
29. More powerful/flexible runtime Deferred Loading (aka lazy loading) Foreign Keys surfaced More complete LINQ implentation ExecuteStoreQuery EntityFunctions and SqlFunctions Improvements to generated SQL
36. Objects trump Tables Use LINQ Use an ORM I don’t really care which. But Nhibernate and Entity Framework are good candidates Use an ORM wisely
37. Resources Slides, links and more http://geekswithblogs.net/iupdateable Entity Framework 4.0 Resources http://bit.ly/ef4resources
Editor's Notes
http://en.wikipedia.org/wiki/Object-relational_impedance_mismatchhttp://www.agiledata.org/essays/impedanceMismatch.htmlTechnical and Culturalhttp://en.wikipedia.org/wiki/Abstraction_layerhttp://en.wikipedia.org/wiki/Abstraction_(computer_science)
Started in 70sODBMS 19852004 rise with open sourcedb4o
Anti in the MS camp http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx
LLBLGen Pro http://www.llblgen.com/Nhibernatehttp://www.hibernate.org/343.htmlEntitySpaceshttp://www.entityspaces.net/Portal/Default.aspxOpen Access http://www.telerik.com/products/orm.aspxDevForcehttp://www.ideablade.com/XPO http://www.devexpress.com/Products/NET/ORM/Lightspeedhttp://www.mindscape.co.nz/products/LightSpeed/default.aspxPlus many, many moreOf 31 .NET ORMs in 2003, 9 lasted to 2008
DevForce now target Entity Framework, replacing their ownLLBLGen v3 will target Entity Framework as well as their ownDevart Entity Developer
Talking Points: When we talk about the Entity Framework, we’re actually talking about two things: The Entity Data Model (EDM) The Entity Framework It’s important to delineate the two as separate, but complementing technologies The EDM is a set of layers that make up your application’s model, as well as it’s mapping to an underlying data store. Made up of three files: CSDL (Conceptual Schema Definition Language) MSL (Mapping Specification Language) SSDL (Storage Schema Definition Language) This separation of concerns allows great flexibility: Model your application the way you want regardless of the state/structure of its underlying data store Normalize your database as much as you need without worrying about affecting the interface of the application’s object model The EDM represents a re-useable application model that can be leveraged from within many applications/environments and persisted across numerous databases. The Entity Data Model is RDMS agnostic, and numerous database vendors are currently developing providers: Oracle, DB2, MySQL, PostgreSQL, VistaDB, SQLite, Sybase, Informix, etc. The Entity Data Model primarily of three main concepts: Entities, which represent your domain objects. Associations, which represent a relationship between two entities. Functions, which represent stored procedures or UDFs in your database that can be mapped to model-level functionality. Because there will be plenty of situations where you’ll need to use stored procedures, the Entity Data Model allows you to map functions in your model to a store procedure in your database. This is useful because you can leverage a stored procedure without having to write ADO.NET code to call it, you can simply call a function on your model. EDM functions are represented as methods on your ObjectContext class.
Estimated Time: 3 minutesTalking Points: This diagram helps to illustrate how each of the Entity Framework’s query options relate to each other. At the core of it all is the database-specific provider. This layer is what translates the query into the SQL flavor required for the underlying data source. Above that is the Entity Client API, which takes the Entity Framework query and passes in down to the database specific provider. If you want to use the Entity Client API directly, you see that you’re only query option is Entity SQL, and because it sits below Object Services, you don’t get any of its benefits. If you want to materialize your queries as objects, and get things like change tracking, identity mapping, relationship loading, etc. then you would use object services, that delegates its queries down to the Entity Client layer. When using Object Services you can leverage both Entity SQL and LINQ to make your queries.
Code GenIn V1 we had EntityClassGenerator which could be configured using eventsHard (it used CodeDom)Inflexible (not much control)In V2 we will haveTemplatedEntityClassGenerator and will ship default T4 templatesCustomization via ToolsUses Workflow FoundationComplex typesPluralizationPublic abstract PluralizationServiceDefault implementation is English OnlyDefault rules:EntityTypes / ComplexTypes are singularizedEntitySets are pluralizedNavigation Properties based on cardinalityStored ProceduresStored Procedures as functionsMapping support for stored procedure resultComplex type as return typeScalar and void return typeEntity CUD using Stored ProceduresNo need to have SPs for all CUD
Foreign KeysIndependent Association – v1 Product p = new Product { ID = 1, Name = "Bovril", Category = context.Categories .Single(c => c.Name == "Food") }; context.SaveChanges(); FK Association – v2 Product p = new Product { ID = 1, Name = "Bovril", CategoryID = 13 }; context.Products.AddObject(p); context.SaveChanges();Deferred LoadingCan do lazy loadContext.deferredloading=true Model Level using ESQL<Function Name=“CustomerFullName” ReturnType=“String”><Parameter Name=“customer” Type=“MyModel.customer”> <DefiningExpression>customer.FirstName + ‘ ‘ + customer.LastName </DefiningExpression> </Function>Enables from c in ctx.Customers select c.FullName()CLR Level [EdmFunction("MyModel", "CustomerFullName")] public static string FullName(this customer c) { return String.Format("{0} {1}", c.FirstName, c.LastName); }Enables Console.WriteLine(c.FullName());Inline Functions in ESQL using Northwind;function AmountPurchased(c Customer) as Sum (c.Sales.Amt)function AmountReturned(c Customer) as Sum (c.Returns.Amt)function AmountConsumed(c Customer) as AmountPurchased(c) – AmountReturned(c)select AmountConsumed(c) from Customers as c;
Code OnlyNo XML files, no model!Convention to configE.g. Convention: xxxID to a primary key, schema=dboE.g. Config: On map to schema sys and class property to table column[TableMapping(Schema=“sys”,TableName=“MyDBTable”][ColumnMapping(PropertyName=“MyClassProp1”, ColumnName=“table_column1”)][Key(PropertyName=“MyClassProp1”)]public objectset<MyThing> MyThings...