1 Entity Framework Introduction. Outline Goals of Entity Framework 2.

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

An Object/Relational Mapping tool Free and open source Simplifies storage of object data in a relational database Removes the need to write and maintain.
.NET 3.5 SP1 New features Enhancements Visual Studio 2008 SP1 New features Enhancements Additional features/enhancements.
Michael Pizzo Software Architect Data Programmability Microsoft Corporation.
.NET Database Technologies: Open-Source Frameworks.
Oct 31, 2000Database Management -- Fall R. Larson Database Management: Introduction to Terms and Concepts University of California, Berkeley School.
Geographic Information Systems
11 3 / 12 CHAPTER Databases MIS105 Lec14 Irfan Ahmed Ilyas.
ORM Technologies and Entity Framework (EF)
A tour of new features introducing LINQ. Agenda of LINQ Presentation We have features for every step of the way LINQ Fundamentals Anonymous Functions/Lambda.
Discover, Master, InfluenceSlide 1 SQL Server Compact Edition and the Entity Framework Rob Sanders Readify.
SQL Server Compact Edition 3.5 and the Entity Framework Rob Sanders and Matt Lynch.
Introduction to ADO Entity Framework ir Denis VOITURON Source:
Eric Nelson Developer & Platform Group Microsoft Ltd
Databases From A to Boyce Codd. What is a database? It depends on your point of view. For Manovich, a database is a means of structuring information in.
Information storage: Introduction of database 10/7/2004 Xiangming Mu.
.NET Database Technologies: Entity Framework additional notes – part 2.
Databases and LINQ Visual Basic 2010 How to Program 1.
LINQ Boot Camp ADO.Net Entity Framework Presenter : Date : Mahesh Moily Nov 26, 2009.
Entity Framework, a quickstart Florin−Tudor Cristea, Microsoft Student Partner.
Zhonghua Qu and Ovidiu Daescu December 24, 2009 University of Texas at Dallas.
Data Access Patterns Some of the problems with data access from OO programs: 1.Data source and OO program use different data modelling concepts 2.Decoupling.
Eric Nelson (or )
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Introduction to Accounting Information Systems
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
Visual Studio 2010 and.NET Framework 4 Training Workshop.
Intro to C#.net and EF Ilan Shimshoni. The Three Faces of ADO.NET The connected layer – Directly connecting to the DB The disconnected layer – Using datasets.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Entity Framework Overview. Entity Framework A set of technologies in ADO.NET that support the development of data-oriented software applications A component.
.NET Database Technologies: Data Models and Patterns.
Ventsislav Popov Crossroad Ltd.. 1. ASP.NET Data Source Controls  SqlDataSource  EntityDataSource  ObjectDataSource 2. Entity Data Model and ADO.NET.
Lecture2: Database Environment Prepared by L. Nouf Almujally & Aisha AlArfaj 1 Ref. Chapter2 College of Computer and Information Sciences - Information.
ADO.NET Entity Framework Mike Taulty Developer & Platform Group Microsoft Ltd
Lap Around Visual Studio 2008 &.NET 3.5 Enhancements.
Lecture2: Database Environment Prepared by L. Nouf Almujally 1 Ref. Chapter2 Lecture2.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 14 Using Relational Databases to Provide Object Persistence (Overview) Modern Database.
CS370 Spring 2007 CS 370 Database Systems Lecture 1 Overview of Database Systems.
Databases Shortfalls of file management systems Structure of a database Database administration Database Management system Hierarchical Databases Network.
Oct * Brad Tutterow. VS 2008.NET 3.5LINQ Entity Framework  The ADO.NET Entity Framework is part of Microsoft’s next generation of.NET technologies.
EntityFrame work and LINQ CH 14. linq LINQ enables you to query data from a wide variety of data sources, directly from your programming code. LINQ is.
Ventsislav Popov Crossroad Ltd.. 1. ASP.NET Data Source Controls  SqlDataSource  EntityDataSource  ObjectDataSource 2. Entity Data Model and ADO.NET.
All information's of PLINQO in this Document, I got it from: So, you could visit the link above to research.
Mr.Prasad Sawant, MIT Pune India Introduction to DBMS.
Declarative Languages and Model Based Development of Web Applications Besnik Selimi South East European University DAAD: 15 th Workshop “Software Engineering.
ADO.NET 3.0 – Entity Data Model Gert E.R. Drapers Chief Software Architect Visual Studio Team Edition for Database Professionals Microsoft Corporation.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
2 Behind every great site, there is great data Eric Nelson Developer Evangelist Microsoft UK
Data Access Methodologies: When to choose what (ADO.NET, Entity Framework, WCF Data Services) Wriju Ghosh Lead Partner Consultant, Microsoft.
uses of DB systems DB environment DB structure Codd’s rules current common RDBMs implementations.
Submitted by: Moran Mishan. Instructed by: Osnat (Ossi) Mokryn, Dr.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
Introduction to Database Programming with Python Gary Stewart
Introduction to Entity framework
Visual Basic 2010 How to Program
Introduction to Entity Framework
Entity Framework DB From Code, OOP Introduction
Entity Framework By: Casey Griffin.
Entity Framework 4 and WCF Data Services 4
ADO.NET Entity Framework Marcus Tillett
ADO.NET Entity Framework
ADO.NEXT Advances in Data Access for 2008
An Introduction to Entity Framework
Chapter 2 Database Environment.
.NET Database Technologies:
Data Model.
Metadata Framework as the basis for Metadata-driven Architecture
ADO.NET Entity Framework
Presentation transcript:

1 Entity Framework Introduction

Outline Goals of Entity Framework 2

Source: Gil Fink The story so far… The “Impedance Mismatch” Relational Database Conceptual / Business Model (Objects) 3

Traditional way.... Make a persistency layer that maps from SQL to OOP It is a better solution than accessing the db from many places in the application But 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 same Etc. 4

ORM’s provides a way to map ORM is: (Wikipedia) A programming technique for converting data between incompatible type systems (such as DBMS) in relational databases and object-oriented programming languages.programmingtype systems relational databasesobject-oriented 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 5

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, commercial TierDeveloper, free ORM and code generation tool Subsonic, open source Source: Bishoy Demian 6

Source: Gil Fink Entity Framework is also a ORM Data access framework Supports data-centric applications and services Enables programming against a conceptual application model Enables independency of any data storage engine or relational schema 7

Source: Gil Fink Programming Against a Model EF uses a model called an Entity Data Model (EDM) EDM is a client-side data model EDM is an abstraction layer on top of the data storage Remove the pain of Interacting with the data storage Translating the data into objects 8

Source: Jeff Derstadt Entity Framework in a Nutshell Goal: Simple and seamless data access for the.NET platform Better layering Better re-use of existing knowledge and assets EDM – Entity Data Model An abstract model for defining entities and relationships Includes schema and mapping Store Schema Definition (SSDL) Conceptual Schema Definition (CSDL) Mapping Schema between the two (MSL) Entity Framework An implementation of EDM and an ORM layer on top A framework for using entities over data 9

Source: Jeff Derstadt Data Store The Entity Framework has no knowledge of the database that stores the data It connects and interacts with the database through a provider that is usually declared in the configuration file As in ADO.NET the providers are supplied by the dbms vendors Some supported dbms’es: SQLServer ;-) Oracle MySQL postgreSQL db

Source: Jeff Derstadt Getting Started DB Model Code DB Model Code DB Model Code Design time 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)

Source: Jeff Derstadt What’s New in.NET 4.0 There’s more! Self-tracking entities SQL generation improvements ObjectStateManager control WPF designer integration SPROC import improvements Model defined functions Code-Only development (Feature CTP) Model-first development Automatic pluralization Lazy loading POCO class support T4 Code Generation Template customization ObjectSet/IObjectSet Foreign keys in models Virtual SaveChanges ExecuteStoreQuery ExecuteStoreCommand More LINQ operator support 12

Demo: Database first How to create an entity model from an existing database 13

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

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

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

Source: Gil Fink The Designer Window Graphical representation of an EDM and its members Enables adding more features to the model Enables properties configuration Enables updating from the data store Enables model validation 17

Entity in the designer Singularization and pluralization: The ‘many’ part is named in plural, e.g. Orders The ‘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. 18

The EDM Document consists of 3 parts The 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 entities Storage 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). 19

The relationships are declared in XML The output of the designer is an XML document that consists of 3 parts: 20 Source: Julia Lerman

Code Generation Entity classes are automatically generated from the EDM The classes consists primary of properties and events So it is possible to get and set values, and to get notified when an event occurs, e.g. an update 21

Use the generated code You 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.entity And add ‘using’ for your EDM in the code where the context class is used The 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 22

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

Source: Gil Fink 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 book Programming Entity Framework, 1st Edition

Querying You can query the model in different ways: Using LINQ Using Entity SQL With Object Services With Entity Client 25

Querying with LINQ Straight forward LINQ syntax IntelliSense support 26 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); 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);

Entity SQL with Object Services T-SQL-like query language EF translates Entity SQL into storage-specific queries Lazy queries No IntelliSense support 27 String queryString VALUE c FROM Customers AS c WHERE c.Country='UK'"; var customers = Context.CreateQuery (queryString); foreach (Customer c in customers) Console.WriteLine(c.CompanyName); String queryString VALUE c FROM Customers AS c WHERE c.Country='UK'"; var customers = Context.CreateQuery (queryString); foreach (Customer c in customers) Console.WriteLine(c.CompanyName);

Entity SQL with client queries Works like traditional PODA: Get a set of records from the data store E.g. like SQLClient or OracleClient No IntelliSense support 28 using (var conn = new EntityConnection("name=NWEntities")) { conn.Open(); var qStr 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)); } using (var conn = new EntityConnection("name=NWEntities")) { conn.Open(); var qStr 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)); }

Mutation Changes to entities are stored in memory: Every entity in ObjectContext has a ObjectStateEntry ObjectContext uses ObjectStateEntries to track entity changes The context.SaveChanges() method is used to update the database according to ObjectStateEntries Rollback (in memory) can be done with context.SaveChanges(false) The normal mutations insert, update and delete are possible 29

Insert Create a new instance (entity) of the class. Evt. set references to related objects (as normal in oop) Add the entity to the context. 30 Console.WriteLine("Create new order"); var order = new Order { CustomerID = "SEVES", EmployeeID = 1 }; context.AddToOrders(order); context.SaveChanges(); Console.WriteLine("Create new order"); var order = new Order { CustomerID = "SEVES", EmployeeID = 1 }; context.AddToOrders(order); context.SaveChanges();

Update Just get a reference to the entity Make the changes And call context.SaveChange() 31 Console.WriteLine("Changing order"); var order = from o in context.Orders where o.OrderID == select o; order.Single().OrderDate = DateTime.Now; context.SaveChanges(); Console.WriteLine("Changing order"); var order = from o in context.Orders where o.OrderID == select o; order.Single().OrderDate = DateTime.Now; context.SaveChanges();

Delete Get a reference to the entity Call context.DeleteObject(theEntity) Call context.SaveChanges() 32 Console.WriteLine("Deleting order"); var order = from o in context.Orders where o.OrderID == select o; context.DeleteObject(order.Single()); context.SaveChanges(); Console.WriteLine("Deleting order"); var order = from o in context.Orders where o.OrderID == select o; context.DeleteObject(order.Single()); context.SaveChanges();

Inheriance To types of inheriance Table-per-Hierarchy Inheritance Table-per-Type Inheritance These covers two different situations in SQL databases without O/R In 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 33

Demo: Table-per-Hierarchy Inheritance Example based on School database from msdn Source: Associations-with-Entity-Framework-Part-1.aspx 34

Demo: Table-per-Type Inheritance Example based on School database from msdn Source: Associations-with-Entity-Framework-Part-2.aspx 35

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

Get the picture ;-) 37 //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 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()); //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());