La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Sonora.Net – Ernesto Ibarra

Presentaciones similares


Presentación del tema: "Sonora.Net – Ernesto Ibarra"— Transcripción de la presentación:

1 Sonora.Net – Ernesto Ibarra
Entity Framework Sonora.Net – Ernesto Ibarra

2 Temario Que es Entity Framework y sus componentes? Que es un ORM?
Principales ORM del Mercado Que es un EntityObject? Que es un POCO Object? Que es Linq? Implementación Básica de Entity Framework Ventajas y desventajas de usar Entity Framework Consideraciones para Performance Preguntas?

3 Que es Entity Framework?
Entity Framework (EF) es un ORM (object- relational mapper) que permite a los desarrolladores en .NET trabajar con datos relacionales usando objetos específicos del dominio. Elimina la necesidad de escribir la mayoría de código de acceso a datos. Es un mecanismo automatizado para acceder y consultar datos en una base de datos y trabajar con los resultados.

4 Componentes de Entity Framework
EDM (Entity Data Model) Conceptual Model Storage Model Mapping LINQ to Entities Entity SQL Object Service Entity Client Data Provider ADO.Net Data Provider EDM (Entity Data Model): EDM consist three main parts- Conceptual model, Mapping and Storage model.   Conceptual Model: Conceptual model is your model classes and their relationships. This will be independent from your database table design. Storage Model: Storage model is your database design model which includes tables, views, stored procedures and their relationships and keys. Mapping: Mapping consist information about how your conceptual model is mapped to storage model. LINQ to Entities: LINQ to Entities is query language used to write queries against the object model. It returns entities which are defined in the conceptual model. You can use your LINQ skills here. Entity SQL: Entity SQL is again a query language same as LINQ to Entities. However it is little more difficult than L2E and also developer need to learn it separately. Object Service: Object service is a main entry point for accessing data from database and to return it back. Object service is responsible for materialization which is process of converting data returned from entity client data provider (next layer) to an entity object structure. Entity Client Data Provider: The main responsibility of this layer is to convert L2E or Entity SQL queries into SQL query which is understood by underlying database. It communicates with ADO.Net data provider which in turn sends or retrieves data from database. ADO.Net Data Provider: This layer communicates with database using standard ADO.Net.

5 Que es un ORM? Object-Relational Mapping
Mapeo objeto-relacional (más conocido por su nombre en inglés, Object- Relational mapping, o sus siglas O/RM, ORM, y O/R mapping) es una técnica de programación para convertir datos entre el sistema de tipos utilizado en un lenguaje de programación orientado a objetos y la utilización de una base de datos relacional, utilizando un motor de persistencia. Nota: En la práctica esto crea una base de datos orientada a objetos virtual, sobre la base de datos relacional. Esto posibilita el uso de las características propias de la orientación a objetos (básicamente herencia y polimorfismo)

6 Principales ORM del Mercado
Java: EJB, Hibernate, Athena Framework, Java Data Objects. .NET: ADO.NET Entity Framework, Linq to SQL, nHibernate, DataObjects.NET. PHP: CakePHP, FuelPHP, Qcodo, Readbean, Zend Framework Phyton: Django, SQLObject, Storm, Tryton. Ruby: ActiveRecord, Datamapper, iBATIS

7 Que es un Entity Object? Por default el Entity Data Model genera EntityObjects que son derivados de entidades (tablas/vistas) EntityObject: By default, the ADO.NET Entity Data Model tools generate EntityObject derived entities. If you check entities created in previous step, it is of this type. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework. If you are working with architectures that require persistence ignorance (for example, test- driven development or domain-driven development) or you have existing domain classes, consider using POCO or POCO proxies.

8 Que es un POCO Object? POCO (Plain Old CLR Object):
- Las clases POCO es una clase la cual no depende de ninguna clase base de un Framework especifico. POCO (Plain Old CLR Object): POCO class is the class which doesn’t depend on any framework specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects”. The Entity Framework 4.0 enables you to use existing .net classes together with the data model without making any modifications to the existing .net classes. These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as EntityObject derived entities .

9 Que es Linq? Definición: Languaje Integrated Query
Linq simplemente es una expresión tipo Query en nuestro código, similar a un Query de SQL en nuestra base de datos. Es aplicable sobre colecciones: Listas Arreglos XML Tablas de base de datos

10 Acceso a datos con ADO.NET

11 Acceso a datos con Linq:
Fácil: List<Customer> customers = from c in Customers where c.FirstName == “Test” select c; Rápido de codificar y legible: List<Customer> customers = dbContext.Customers.Where(c => c.FirstName == “Test”).ToList();

12 Linq vs Native SQL Ventajas:
No hay cadenas mágicas como las que se pueden generar en sentencias SQL (Prevención de Inyección). Intellisense. Un desarrollo mas rápido. Autogeneración de objetos de dominio que pueden ser proyectos reusables. Lazy loading.(Cargado de objetos relacionados sobre demanda) Lambda expressions y extension methods.

13 Linq vs Native SQL Desventajas: Depuración (Debugging).
Consultas complejas traen como resultado problemas de rendimiento. Sobrecarga al crear consultas. Los Índices de base de datos no son usados adecuadamente.

14 Estilos a seguir en Entity Framework
Code First Model First Database first Code First: In the Code First approach, you avoid working with visual model designer (EDMX) completely. You write your POCO classes first and then create database from these POCO classes. Developers who follow the path of Domain-Driven Design (DDD) principles prefer to begin by coding their classes first and then generating the database required to persist their data.   One important thing to understand is that there are two new types introduced for Code First approach, DbContext and DbSet. DbContext is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model. DbSet(Of TEntity) is a simplified alternative to ObjectSet(Of TEntity) and is used to perform CRUD operations against a specific type from the model in Code First approach. Please visit EF Code-First Tutorial to learn code first in detail. Model First: In Model First approach, you create Entities, relationships, and inheritance hierarchies directly on the design surface of EDMX. So in Model First approach, when you add ADO.NET Entity Data Model, you should select ‘Empty Model’ instead of ‘Generate from database’.

15 Implementacion Basica de EF
Demostración

16 Consideraciones para Performance
Múltiples Entity Models (múltiples contextos). Desactivar el trackeo si no es necesario (Mejora el rendimiento): SubwayDB context = new SubwayDB(); context.Configuration.AutoDetectChangesEnabled = false; // Do bulk insert // Change it back context.Configuration.AutoDetectChangesEnabled = true; Usar SQL Projection: var users = from u in context.UserAccounts where u.Active == true select new { FirstName = u.FirstName, LastName = u.LastName, = u. };

17 Consideraciones para Performance
Usar el tipo de coleccion apropiado: IQueryable<UserAccount> IEnumerable<UserAccount> - Filtra desde la base de datos Filtra desde el lado del cliente - Soporta Lazy loading No soporta Lazy loading. Usar Queries compilados: Aplicar a los Queries comunmente utilizados para mejorar el rendimiento (Performance). Usar Paginados de información del lado del servidor: int pageSize=10,startingPageIndex=2; var users = context.UserAccounts.Take(pageSize).Skip(startingPageIndex * pageSize) .ToList();

18 Consideraciones para Performance
Caching: - Caching Interno Rápida ejecución estilo Micro-ORM estilo Sql Query en base de datos y ExecuteStoreQuery (SP): var query = ContextManager.CurrentContext.Database.SqlQuery<TransactionObjectList>( "EXEC " @StoreNumber, " sqlparameters); Lazy Vs Eager loading (Cuando seleccionar Lazy loading)

19 Consideraciones para Performance
Evitar el uso del método Contains En Linq, el método Contains es usado para verificar la existencia de un valor. Este es convertido a una sentencia “WHERE IN” en SQL, lo cual causa una degradación del performance. Depuración y Optimización de Linq Query: - Usar SQL Profiler - Dividir la consulta a múltiples consultas (múltiples sentencias JOIN a tablas) Estrategias para manejo de Herencia en Entity Framework: - Jerarquía por Tabla (TPH) - Tabla por Tipo (TPT) - Tabla por Clase concreta (TPC):

20 Consideraciones para Performance
Jerarquía por Tabla (TPH) - Permite polimorfismo por de-normalización de esquema de SQL y utiliza una columna como tipo discriminador que contiene esta información. Discriminador = 3 Tipos

21 Consideraciones para Performance
Tabla por Tipo (TPT) - Representa una relación tipo “is a” (herencia), como una relación tipo “has a” (Foreign key).

22 Consideraciones para Performance
Tabla por Clase Concreta (TPC) - Descarga las relaciones de polimorfismo y herencia completamente desde el esquema SQL.

23 Referencias: ADO.NET Entity Framework: Entity Framework Tutorial:
Entity Framework Tutorial: PluralSight Online Trainings: getting-started Entity framework: Mostafa Darwiche

24


Descargar ppt "Sonora.Net – Ernesto Ibarra"

Presentaciones similares


Anuncios Google