Download EF Code Firstx

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Microsoft SQL Server wikipedia , lookup

Concurrency control wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
building software to
help our clients grow
SINCE 1985
(How to) Put your Code First
with Entity Framework
Max Weber – Architect
www.tallan.com
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
 EDM
on the Entity Data Model (EDM)
borrows from Entity-Relationship Model
 Current
version is v4.0 (Shipped with VS2010)
Entity Framework set up shop where?
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
Entity Framework’s supply chain
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
 Link

from MSDN
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 UserId in Users table
Associations
 One-To-Many
 Users have

public virtual ICollection<Post> Posts { get; set; }
 Posts have

many posts
many comments
public ICollection<Comment> Comments { get; set; }
Associations
 One-to-One
 Comments have

an author (User)
public virtual User Author {get; set;}
Associations
 Many-To-Many
 Posts

public virtual ICollection<Tag> Tags { get; set; }
 Tags

can contain many Tags
can be applied to many posts
public virtual ICollection<Post> Posts { get; set; }
Lazy Loading
 Standard
Loading
 public class user

public ICollection<Post> Posts { get; set; }
 Lazy
Loading
 public class User

public virtual ICollection<Post> Posts { get; set; }
Database generation
 Turning
 You
it off
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:
 protected override
 Useful
void Seed(DatabaseContext context)
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
 public CodeBookContext() : base("SocialNotWork")
 Change table names
 [Table("CaptchaType", SchemaName = "sec")]
public class CaptchaTypeTest
 Field mapping
 [Column(Name="CaptchaTypeID", Order=1)]
public int CaptchaID { 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


Assembly
 System.ComponentModel.
DataAnnotations
Annotations
 Key
 MaxLength
 MinLength
 Column
 StringLength
 InverseProperty
 NotMapped


More Annotations
 ForeignKey
 ConcurrencyCheck
 Required
Class-level
 ComplexType
 Table
Inheritance Mapping
 Impedance
 “is
mismatch: OO vs. Relational design
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
 That
one should I use?
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
 Morteza Manavi’s blog
 The Morning Brew (Developer News)
If you remember one thing from this presentation:
Cycling is the new “Golf”
Tallan, Inc. Proprietary and Confidential. Copyright 2010.
5/22/2017
35
WCF Data Services
Bonus Slides Section #1
Architecture Overview :
WCF Data Services
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
 Roll
 Link
Provider
your own
to WCF Data Services Providers

http://msdn.microsoft.com/en-us/library/dd672591.aspx
Override Configuration
Bonus Slides Section #2
Fluent API: Model Configuration



Primary Keys
 Simple or Composite
Properties
 CLR-Nullable to required
 Override string length
 Switch off identity
 Ignore property
Types
 Complex Type

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
Changing conventions
 It
can be done
 Factory classes for conventions just need to be
rerouted to other classes (or something)