430 likes | 1.12k Views
( How to) Put your Code First with Entity Framework. Max Weber – Architect. We thank the following companies for their gracious sponsorship. Platinum Sponsor. Gold Sponsors. Silver Sponsors. Distribution of slide deck. This slide deck will be made available from the following locations:
E N D
(How to) Put your Code First with Entity Framework Max Weber – Architect
We thank the following companies for their gracious sponsorship Platinum Sponsor Gold Sponsors Silver Sponsors
Distribution of slide deck • This slide deck will be made available from the following locations: • Tallan blogs - blogs.tallan.com • Code Camp NYC - nyc.codecamp.us
Our Agenda • Brief introduction to Entity Framework (EF) • Intro to EF Code First • Talking about, then coding: • Entities and Associations • Adding Metadata / annotations • Validation • Database Initializers / seeding / testing • Inheritance Mapping • Drawbacks • Summary
What is Entity Framework? (Abridged) • Based on the Entity Data Model (EDM) • EDM borrows from Entity-Relationship Model • Current version is v4.0 (Shipped with VS2010)
What is the Entity Data Model? • Entity Data Model • The Entity Data Model (EDM) is a set of concepts that describe the structure of data, regardless of its stored form. The EDM borrows from the Entity-Relationship Model described by Peter Chen in 1976, but it also builds on the Entity-Relationship Model and extends its traditional uses. • Extensions to E-R Model: • Separation of the entities and relationships from their storage medium • http://msdn.microsoft.com/en-us/library/ee382825.aspx
Data Providers – Entity Framework 4 • EF uses the ADO.NET Data Provider model • Providers • MS SQL Server • Indirect access to other DBs using ODBC, OLEDB • VistaDB • Devart • OpenLink Software • Synergy • …5+ more • ADO.NET Data Providers List • http://msdn.microsoft.com/en-us/data/dd363565.aspx
EF: What comes first? • Database First • Create model from database • Designer / XML files • Model First • Create database from model • Designer / XML files • Code First • Create database from model • Code-only interface • Available exclusively in “Magic Unicorn” Edition
Magic Unicorns? Seriously? • Based on Entity Framework “Magic Unicorn Edition” (Thanks Scott Hanselman) • CTP5 – minimal breaking changes left • Next version: RTW (Q1 2011) • Version is basically, EF4 SP1 or EF5 • Code interface instead of XML to EF
How do I land myself a Magical Unicorn? • NuGet Package Manager (VS 2010) (recommended) • Download extension then install package “EFCodeFirst” • Download from MSDN • Link here. • (The link really isn’t presentation-friendly)
What the DbContext? • DbContext • Inherits from ObjectContext • Lightweight context for database • DbSet • Inherits from ObjectSet • Lightweight version • Fewer options to choose from
Convention over Configuration • public class MyAppContext : DbContext • Default Connection String: “MyAppContext” • Creates database if one doesn’t exist • Default database order: SQL Express, SQLCE, SQL Server • DbSet<User> Users { get; set; } • Maps to “Users” table • Id (int) • Marked as primary key • identity column • Stored as UserIdin Users table
Associations • One-To-Many • Users have many posts • publicvirtualICollection<Post> Posts { get; set; } • Posts have many comments • publicICollection<Comment> Comments { get; set; }
Associations • One-to-One • Comments have an author (User) • publicvirtualUser Author {get; set;}
Associations • Many-To-Many • Posts can contain many Tags • publicvirtualICollection<Tag> Tags { get; set; } • Tags can be applied to many posts • publicvirtualICollection<Post> Posts { get; set; }
Lazy Loading • Standard Loading • public class user • publicICollection<Post> Posts { get; set; } • Lazy Loading • public class User • publicvirtualICollection<Post> Posts { get; set; }
Database generation • Turning it off • You can turn it off • Database Initialization (IDatabaseInitializer) • DropCreateDatabaseAlways • CreateDatabaseIfNotExists • DropCreateDatabaseIfModelChanges • Better Migration support is supposed to be coming!
Seeding Data • In your Database Initializer class: • protectedoverridevoidSeed(DatabaseContext context) • Useful for testing • Specify connection string + DropCreateDatabaseAlways= consistency + isolation
Complex Types • Complex type = entity with no key • Automatic registration of a complex type: • No key can be inferred through convention • No primary key annotation / fluent API • Explicit registration of a complex type: • [ComplexType] annotation • ComplexType<>() Fluent API • Restrictions • Values must be scalar (no referencing allowed!) • Must be initialized in parent entity
Overriding Convention • Examples • Change database connection string / name • publicCodeBookContext() : base("SocialNotWork") • Change table names • [Table("CaptchaType", SchemaName = "sec")]publicclassCaptchaTypeTest • Field mapping • [Column(Name="CaptchaTypeID", Order=1)]publicintCaptchaID { get; set; }
Validation • Validation via ValidationAttribute(s) • [StringLength] • [Required] • [MaxLength] • [RegularExpression] • Entity or ComplexType validation • Honors IValidatableObject interface • Validating • Context.SaveChanges() invokes automatically • Get validation errors with Context.GetValidationErrors()
Data Annotations • More Annotations • ForeignKey • ConcurrencyCheck • Required • Class-level • ComplexType • Table • Assembly • System.ComponentModel.DataAnnotations • Annotations • Key • MaxLength • MinLength • Column • StringLength • InverseProperty • NotMapped
Inheritance Mapping • Impedance mismatch: OO vs. Relational design • “is a” vs. “has a”: Bridge the gap! • Three types of Inheritance Mapping • Table Per Hierarchy (TPH) • Table Per Type (TPT) • Table Per Concrete Class (TPC) • Which one should I use? • That depends…
Table Per Hierarchy (TPH) • Table Per Hierarchy (TPH) • Use one table for all types (denormalize schema) • Class type determined by “Discriminator” • Discriminator value can be overridden for values and data types • This is the default convention • Cons • (DBA starts to yell at you because…) • Sub-class fields not enforced in database (NOT NULL) • Violates 3NF • Sub-class values dependent on Discriminator value
Table Per Type (TPT) • Table Per Type (TPT) • Base table for base class • One table per derived type (differential) • Implementation • Table annotation on subtypes • fluent API via ToTable • Cons • Ugly generated SQL when querying for base class • Reporting more difficult due to normalized structure
Table Per Concrete Class (TPC) • Table Per Concrete Class (TPC) • No base table for base class • One table per type contains all information • No VS2010 EDM designer support; EF runtime support • Implementation • One table per concrete type, no column sharing • No relationships; database is unaware • Fluent API: MapInheritedProperties() + ToTable() • Cons • Difficult migration / change process
Inheritance Mapping • Which one should I use? • TPH • Behavior (not structure) is main differentiator of sub-classes • TPT • Structure (not behavior) is main differentiator of sub-classes • TPC • Base class rarely/never directly queried (for top level) • Query of concrete objects is high/the norm • Can use more than one method in a hierarchy • TPT vs. TPC – JOIN vs. UNION
We also call these opportunities… • Drawbacks • (no) Stored procedure support • (no) Generation of classes from existing database (Code First stack) • (no) Enums (future release, not in EF at all) • WCF Data Services hack (not sure if issue still) • Internationalization conventions (maybe for RTW)
EF4 Code First Workaround ideas • The “stored procedure” issue • Start out with EF Code First • Circle the wagon when stored procedures / other features are needed • Database First, refine model, generate POCO classes • WCF Data Services • Wait for RTM (if the problem still exists in CTP5) • Creativity is key! Share / monetize your ideas!
Summary • EF: I have an idea (about what it is) • EF Code First – code wags database • Convention over configuration = efficiency + flexibility • Inheritance Mapping tackles OO/Relational impedance mismatch • Not perfect • EF Code First not done (as of 2/18) • Availability by end of Q1 2011
You can Dig Deeper with these Handy Resources • Entity Framework FAQ • EF Design blog • ADO.NET team blog • EF on MSDN Library • EF on MSDN Data Development Center • Julie Lerman’s blog • Scott Guthrie’s blog • Scott Hanselman’s blog • MortezaManavi’s blog • The Morning Brew (Developer News)
Cycling is the new “Golf” Tallan, Inc. Proprietary and Confidential. Copyright 2010.
WCF Data Services Bonus Slides Section #1
Open Data Protocol (OData) • Definition • OData enables you to expose your data as resources that are addressable by URIs • Enables you to access and change data by using the semantics of representational state transfer (REST) • Standard HTTP verbs supported: • GET, PUT, POST, DELETE. Reference: WCF Data Services Overview - http://msdn.microsoft.com/library/cc668794.aspx
Output Formats – WCF Data Services • Atom • JSON • XML
Freedom of data source – WCF Data Services • Entity Framework Provider • Uses Entity Data Models to structure access • Reflection Provider • Exposes data structures with interface IQueryable • Create/Update/Delete with interface IUpdatable • Custom Provider • Roll your own • Link to WCF Data Services Providers • http://msdn.microsoft.com/en-us/library/dd672591.aspx
Override Configuration Bonus Slides Section #2
Fluent API: Model Configuration • Relationships • One to Many • Many to One • Turn off cascade delete • Composite foreign key • Rename FK • Rename Many:Many cols • Mapping (Table, Cols) • Change names • Inheritance • Link to Fluent API page • Primary Keys • Simple or Composite • Properties • CLR-Nullable to required • Override string length • Switch off identity • Ignore property • Types • Complex Type
Changing conventions • It can be done • Factory classes for conventions just need to be rerouted to other classes (or something)