Entity Framework Core

Angel Soto

 

dreamensys@gmail.com

@dreamensys

Full Stack Developer

  • Qué es EF?
  • Ventajas y desventajas?
  • Tipos de modelo(Code First vs Database first)
  • Cadenas de conexion
  • Migraciones
  • Constraints(Data annotations vs Fluent API)
  • Siembra de datos
  • Relacion entre tablas

Qué es EF

Entity Framework Core es una versión ligera, extensible y multiplataforma del mapeador objeto-relacional (ORM) de Microsoft, Entity Framework es la plataforma oficial de acceso a datos de Microsoft.

 

Ventajas

  • Facilidad
  • LINQ
  • Soporte procedimientos almacenados.
  • Mapeos
  • Table Splitting
  • Transacciones
  • Soporta proveedores como: SQL Server, MySQL y PostgreSQL entre otros.

Desventajas

  • Performance
  • Alto acoplamiento
  • Más lento que ADO.NET

Tipo de modelo

Cadenas de Conexión

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=IntecapBooksTemplate;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  • Server
  • Database
  • Trusted_Connection
  • Otros más

Migraciones

public partial class AddPhoneNumber : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<string>(
            name: "PhoneNumber",
            table: "Customers",
            nullable: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "PhoneNumber",
            table: "Customers");
    }
}

Relaciones entre tablas

public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }
    public AuthorBiography Biography { get; set; }
}
+-
public class AuthorBiography
{
    public int AuthorBiographyId { get; set; }
    public string Biography { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}

1.Uno a uno

Relaciones entre tablas

public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }
    public List<Book> Books { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}

2.Uno a muchos

Relaciones entre tablas

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public List<Category> Categories { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public List<Book> Books { get; set; }
}

3.Muchos a muchos

Constraints

public class Blog
{
    public int BlogId { get; set; }
    [Required]
    public string Url { get; set; }
}

Data Annotations

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired();
    }
}

Fluent API

los más usados...

Constraint Ejemplo
Required
Key
ConcurrencyCheck
NotMapped
MaxLength
[Required]
public string Url { get; set; }
[Key]
public int OrderDetailID { get; set; }
[ConcurrencyCheck]
public string Version { get; set; }
[NotMapped]
public class BlogMetadata
[MaxLength(50)]
public string LastName { get; set; }
Constraint Ejemplo
MinLength
StringLength
ForeignKey
Table
Column
RegularExpression
[MinLength(3)]
public string LastName { get; set; }
[StringLength(50)]
public string LastName { get; set; }
[ForeignKey("OrderID")]
public Order Order { get; set; }
[Table("UserInfo")]
public class Person
[Column("LName")]
public string LastName { get; set; }

entre otros...

[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")]
public object LastName;

Constraints(Fluent API)

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired();
    }
}

Siembra de datos

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Author>().HasData(
        new Author
        {
            AuthorId = 1,
            FirstName = "William",
            LastName = "Shakespeare"
        }
    );
    modelBuilder.Entity<Book>().HasData(
        new Book { BookId = 1, AuthorId = 1, Title = "Hamlet" },
        new Book { BookId = 2, AuthorId = 1, Title = "King Lear" },
        new Book { BookId = 3, AuthorId = 1, Title = "Othello" }
    );
}

Otros conceptos...

  • Lazy Loading
  • Explicit Loading
  • Eager loading
  • Tracking
  • N+1 problem
Made with Slides.com