2. El momento en que quieres dejarlo es justo el
momento en que tienes que seguir avanzando
3. Objetivo
1. Adquirir los conceptos
básicos relacionados con
Visual Studio
2. Reconocer las
características de Visual
Studio
● 2.2 Entity Framework
Contenido
4. ODS
● 4.3 De aquí a 2030, asegurar
el acceso igualitario de todos
los hombres y las mujeres a
una formación técnica,
profesional y superior de
calidad, incluida la enseñanza
universitaria
META
6. Qué 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.
7. 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
8. 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)
10. Que es un Entity Object?
● Por default el Entity Data
Model genera EntityObjects
que son derivados de
entidades (tablas/vistas)
11. 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.
12. 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
14. 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();
15. Linq vs Native SQL
● Ventajas:
1. No hay cadenas mágicas como las que se pueden generar en sentencias
SQL (Prevención de Inyección).
2. Intellisense.
3. Un desarrollo mas rápido.
4. Autogeneración de objetos de dominio que pueden ser proyectos reusables.
5. Lazy loading.(Cargado de objetos relacionados sobre demanda)
6. Lambda expressions y extension methods.
16. Linq vs Native SQL
● Desventajas:
1. Depuración (Debugging).
2. Consultas complejas traen como resultado problemas de rendimiento.
3. Sobrecarga al crear consultas.
4. Los Índices de base de datos no son usados adecuadamente.
17. Estilos a seguir en Entity Framework
● Code First
● Model First
● Database first
18. 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, Email = u.Email };
19. 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();
20. 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 sp_GetTransactionList @RoleID, @UserID, @RegionID,
@Lookup, @TransactionsStatus, @DateFrom, @DateTo, " + "@AmountFrom, @AmountTo, @DeliveryMethod, @AdminMenu, @StoreNumber, @HasDiscount,
@CateringMenu, " + "@DevelopmentStores, @WithCustomerAbuse, @WithTotalPrice, @minGrandTotal, @maxGrandTotal, @EnteredToSubshop, " +
"@ExcludeZeroBalance, @StoreIsRemoved, @marketID, @Page,@PageSize,@sortdir,@sort", sqlparameters);
● Lazy Vs Eager loading (Cuando seleccionar Lazy loading)
21. 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):
22. 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
23. Consideraciones para Performance
● Tabla por Tipo (TPT)
- Representa una relación tipo “is a” (herencia), como una relación tipo “has a” (Foreign
key).
24. Consideraciones para Performance
● Tabla por Clase Concreta (TPC)
- Descarga las relaciones de polimorfismo y herencia completamente desde el esquema SQL.
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.
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.
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 .
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’.