Entity Framework Introduction

37
1 Entity Framework Introduction

description

Entity Framework Introduction. Outline. Goals of Entity Framework. The story so far…. The “Impedance Mismatch”. ?. Relational Database . Conceptual / Business Model (Objects). Traditional way. Make a persistency layer that maps from SQL to OOP - PowerPoint PPT Presentation

Transcript of Entity Framework Introduction

Page 1: Entity Framework Introduction

1

Entity Framework Introduction

Page 2: Entity Framework Introduction

2

OutlineGoals of Entity Framework

Page 3: Entity Framework Introduction

Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf

The story so far…The “Impedance Mismatch”

Relational Database

Conceptual / Business Model (Objects)

?

3

Page 4: Entity Framework Introduction

4

Traditional way....Make a persistency layer that maps from SQL to OOPIt is a better solution than accessing the db from many places in the applicationBut it still can raise some problems, e.g.:

Tight coupling between application and db(e.g. can not change tables in the db without making changes to domain classes in the application)Hard to maintain (e.g. SQL queries, dependent classes etc. might be spread in many places)Application and db domains are probably not the sameEtc.

Page 5: Entity Framework Introduction

5

ORM’s provides a way to mapORM is:

• (Wikipedia) A programming technique for converting data between incompatible type systems (such as DBMS) in relational databases and object-oriented programming languages.

• It does the plumbing work for you to aggregate, modify and save your data back to its storage in Object Oriented manner (easy to understand, maintain and extend)

Source: Bishoy Demian

Page 6: Entity Framework Introduction

6

ORM external tools for .Net (Wikipedia)NHibernate, open source.netTiers, open source, based on commercial code generation tool (Codesmith)Developer Express, eXpress Persistent Objects (XPO)LLBLGen, open source drivers, commercialTierDeveloper, free ORM and code generation toolSubsonic, open source

Source: Bishoy Demian

Page 7: Entity Framework Introduction

Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf

Entity Framework is also a ORMData access frameworkSupports data-centric applications and services Enables programming against a conceptual application modelEnables independency of any data storage engine or relational schema

7

Page 8: Entity Framework Introduction

8Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf

Programming Against a ModelEF uses a model called an Entity Data Model (EDM)EDM is a client-side data modelEDM is an abstraction layer on top of the data storage Remove the pain of

Interacting with the data storageTranslating the data into objects

Page 9: Entity Framework Introduction

Source: Jeff Derstadt

Entity Framework in a NutshellGoal: Simple and seamless data access for the .NET platform

Better layeringBetter re-use of existing knowledge and assets

EDM – Entity Data ModelAn abstract model for defining entities and relationshipsIncludes schema and mapping

Store Schema Definition (SSDL)Conceptual Schema Definition (CSDL)Mapping Schema between the two (MSL)

Entity FrameworkAn implementation of EDM and an ORM layer on topA framework for using entities over data

9

Page 10: Entity Framework Introduction

10Source: Jeff Derstadt

Data StoreThe Entity Framework has no knowledge of the database that stores the dataIt connects and interacts with the database through a provider that is usually declared in the configuration fileAs in ADO.NET the providers are supplied by the dbms vendorsSome supported dbms’es:

SQLServer ;-)OracleMySQLpostgreSQLdb2...

Page 11: Entity Framework Introduction

Source: Jeff Derstadt

Getting Started

DB ModelCode

DB ModelCode

DB ModelCode

Design time

Design time

Design time

Design time

Runtime Runtime

Model First (VS 2010 and .NET 4.0)

Code First (Entity Framework Feature CTP3)

why? it already exists, or you want low level control over the database

why? you want separation from code and database in a declarative format

why? primarily focused on code shape, database is an implementation detail

11

Database First (VS 2008 and .NET 3.5 SP1)

Page 12: Entity Framework Introduction

Source: Jeff Derstadt

What’s New in .NET 4.0

There’s more!Self-tracking entitiesSQL generation improvementsObjectStateManager controlWPF designer integrationSPROC import improvementsModel defined functionsCode-Only development (Feature CTP)

Model-first developmentAutomatic pluralizationLazy loadingPOCO class supportT4 Code GenerationTemplate customizationObjectSet/IObjectSetForeign keys in modelsVirtual SaveChangesExecuteStoreQueryExecuteStoreCommandMore LINQ operator support

12

Page 13: Entity Framework Introduction

13

Demo: Database firstHow to create an entity model from an existing database

Page 14: Entity Framework Introduction

14

Create a new entity model, step 1Create a class library projectAdd new item, select the ADO.NET Entity Data Model template

Page 15: Entity Framework Introduction

15

Create a new entity model, step 2When database first, select ”Generate From Database”Select the database connectionSelect the database entities that shall be visibleImportant: enable Pluralize... and foreign keys

Page 16: Entity Framework Introduction

16

Create a new entity model, step 3Adjust the entities, mapping etc.

Page 17: Entity Framework Introduction

Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf

The Designer WindowGraphical representation of an EDM and its membersEnables adding more features to the modelEnables properties configurationEnables updating from the data storeEnables model validation

17

Page 18: Entity Framework Introduction

18

Entity in the designerSingularization and pluralization:

The ‘many’ part is named in plural, e.g. OrdersThe ‘one’ part is named in single, e.g. Customer

Navigation Properties:Make it possible to navigate from one entity (in code an object) to another.

Page 19: Entity Framework Introduction

19

The EDM Document consists of 3 partsThe Entity Data Model (EDM) is a schema language for entities. It allows for the definition of entities, relationships between entities and logical sets of related entitiesStorage Metadata Schema (SSDL) is a formal description of the database that persists data for an application built on the Entity Data Model (EDM). The entities and associations declared in this schema are the basis for mapping entities and associations in the conceptual schema to the corresponding entities in the storage model.Mapping Specification (MSL) is used to connect the types declared in conceptual schema definition language (CSDL) to database metadata that persists data.Conceptual Schema (CSDL) is a design template for the object model that will be used by applications built on the Entity Data Model (EDM).

Page 20: Entity Framework Introduction

20

The relationships are declared in XMLThe output of the designer is an XML document that consists of 3 parts:

Source: Julia Lerman

Page 21: Entity Framework Introduction

21

Code GenerationEntity classes are automatically generated from the EDMThe classes consists primary of properties and eventsSo it is possible to get and set values, and to get notified when an event occurs, e.g. an update

Page 22: Entity Framework Introduction

22

Use the generated codeYou should place the EDM and therefore the generated code in a class library (dll-assembly).Then you can access the EDM from your data-tier, business-tier, persistent-tier, etc.When you access from another assembly remember to add a reference to your EDM assembly and to system.data.entityAnd add ‘using’ for your EDM in the code where the context class is usedThe connection string in the app.config must also be in the app-config for the exe-assembly.

But it is easier to see in a demo

Page 23: Entity Framework Introduction

23

Demo: Access EDM assembly Access it from a console applicationDo a simple LINQ query and write the result on screen

Page 24: Entity Framework Introduction

Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf

Querying the Model

• Queries are built against a data model• EDM query transform into data storage query• Query results materialize into model entities

The image is taken from Julia Lerman’s

bookProgramming Entity Framework, 1st Edition

Page 25: Entity Framework Introduction

25

QueryingYou can query the model in different ways:

Using LINQUsing Entity SQL

With Object ServicesWith Entity Client

Page 26: Entity Framework Introduction

26

Querying with LINQStraight forward LINQ syntaxIntelliSense support

var context = new NWEntities(); var query = from c in context.Customers where c.Orders.Count()>25 select c;

foreach(Customer c in query) Console.WriteLine(c.CompanyName);

Page 27: Entity Framework Introduction

27

Entity SQL with Object ServicesT-SQL-like query languageEF translates Entity SQL into storage-specific queriesLazy queriesNo IntelliSense support

String queryString = @"SELECT VALUE c FROM Customers AS c WHERE c.Country='UK'";var customers = Context.CreateQuery<Customer>(queryString);

foreach (Customer c in customers) Console.WriteLine(c.CompanyName);

Page 28: Entity Framework Introduction

28

Entity SQL with client queriesWorks like traditional PODA: Get a set of records from the data storeE.g. like SQLClient or OracleClient No IntelliSense support

using (var conn = new EntityConnection("name=NWEntities")) { conn.Open(); var qStr = @"SELECT VALUE c FROM Customers AS c WHERE c.Country='UK'"; var cmd = conn.CreateCommand(); cmd.CommandText = qStr; using (var rdr = cmd.ExecuteReader()){ while (rdr.Read()){ Console.WriteLine(rdr.GetString(1)); } } }

Page 29: Entity Framework Introduction

29

MutationChanges to entities are stored in memory:

Every entity in ObjectContext has a ObjectStateEntryObjectContext uses ObjectStateEntries to track entity changes

The context.SaveChanges() method is used to update the database according to ObjectStateEntriesRollback (in memory) can be done with context.SaveChanges(false)

The normal mutations insert, update and delete are possible

Page 30: Entity Framework Introduction

30

InsertCreate a new instance (entity) of the class. Evt. set references to related objects (as normal in oop)Add the entity to the context.

Console.WriteLine("Create new order");var order = new Order { CustomerID = "SEVES", EmployeeID = 1 };context.AddToOrders(order);context.SaveChanges();

Page 31: Entity Framework Introduction

31

UpdateJust get a reference to the entityMake the changesAnd call context.SaveChange()

Console.WriteLine("Changing order"); var order = from o in context.Orders where o.OrderID == 11078 select o; order.Single().OrderDate = DateTime.Now; context.SaveChanges();

Page 32: Entity Framework Introduction

32

DeleteGet a reference to the entityCall context.DeleteObject(theEntity)Call context.SaveChanges()

Console.WriteLine("Deleting order"); var order = from o in context.Orders where o.OrderID == 11078 select o; context.DeleteObject(order.Single()); context.SaveChanges();

Page 33: Entity Framework Introduction

33

InherianceTo types of inheriance

Table-per-Hierarchy InheritanceTable-per-Type Inheritance

These covers two different situations in SQL databases without O/RIn the first situation you’ll have one ”type table” where different subtypes are listed.In the second situation you’ll have a specialized table pr. type

Page 34: Entity Framework Introduction

34

Demo: Table-per-Hierarchy InheritanceExample based on School database from msdn

Source: http://mosesofegypt.net/post/Inheritance-and-Associations-with-Entity-Framework-Part-1.aspx

Page 35: Entity Framework Introduction

35

Demo: Table-per-Type InheritanceExample based on School database from msdn

Source: http://mosesofegypt.net/post/Inheritance-and-Associations-with-Entity-Framework-Part-2.aspx

Page 36: Entity Framework Introduction

36

Association – no need to carry the full loadFields that are not used so frequently might be extracted to another entity with a 1-1 relation

Page 37: Entity Framework Introduction

37

Get the picture ;-)

//Get photo when needed AssoEntities assoContext = new AssoEntities(); var employee = (from e in assoContext.Employees select e).FirstOrDefault(); Console.WriteLine(employee.LastName); Console.WriteLine( employee.EmployeePhoto.Photo.Length.ToString());

//Get the photo together with the rest of Employee AssoEntities assoContext = new AssoEntities(); var employee = (from e in

assoContext.Employees.Include("EmployeePhoto") select e).FirstOrDefault(); Console.WriteLine(employee.LastName); Console.WriteLine(

employee.EmployeePhoto.Photo.Length.ToString());