Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chương 5 - Entity Framework

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 35

Trường Đại học Xây dựng Hà Nội

Bộ môn Khoa học Máy tính

Server side application development


Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính

Chapter 5: Entity Framework Core


 Introduction
 Installation
 DbContext, Model, Migration, Fluent API
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Introduction
 What is Entity Framework Core?
 Entity Framework Core is the new version of Entity Framework
after EF 6.x. It is open-source, lightweight, extensible and a cross-
platform version of Entity Framework data access technology.
 EF Core is an object-relational mapper (ORM). Object-relational
mapping is a technique that enables developers to work with data
in object-oriented way by performing the work required to map
between objects defined in an application's programming
language and data stored in relational datasources.
 EF Core is intended to be used with .NET Core applications.
However, it can also be used with standard .NET 4.5+ framework
based applications.
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Introduction
 What is Entity Framework Core?
 The following figure illustrates the supported application
types, .NET Frameworks and OSs.
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Introduction
 Why use an ORM?
 Most development frameworks include libraries that enable access
to data from relational databases via recordset-like data
structures. The following code sample illustrates a typical scenario
where data is retrieved from a database and stored in an ADO.NET
DataTable so that it is accessible to the program's code:

using(var conn = new SqlConnection(connectionString))


using(var cmd = new SqlCommand("select * from Products", conn))
{
var dt = new DataTable();
using(var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Introduction
 Why use an ORM?
 The data within the DataTable is accessible via numeric or string
indexers and needs to be converted from object to the correct
type:
foreach(DataRow row in dt.Rows)
{
int productId = Convert.ToInt32(row[0]);
string productName = row["ProductName"].ToString();
}
 This late-bound or "weakly-typed" approach to data access is
prone to error. Problems commonly arise from mistyping the
name of a column, or finding that the name of the column has
been changed in the database, or from a change to the order in
which fields are specified in the SQL statement without a
corresponding change being made to the application code
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Introduction
 Why use an ORM?
 Strong Typing
• When you take a strongly-typed approach to data, you work with
properties of predefined classes that form a domain model in an
object-oriented way:
public class Product
{
int ProductId { get; set; }
string ProductName { get; set; }
}
int productId = myProduct.ProductId;
string productName = myProduct.ProductName;
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Introduction
 Why use an ORM?
 ORMs are pre-written libraries of code that do this work for you.
Full-featured ORMs do a lot more too. They can:
• map a domain model to database objects
• create databases and maintain the schema in line with changes
to the model
• generate SQL and execute it against the database
• manage transactions
• keep track of objects that have already been retrieved
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Installation
 Install Entity Framework Core
 EF Core is not a part of .NET Core and standard .NET framework. It
is available as a NuGet package. You need to install NuGet
packages for the following two things to use EF Core in your
application:
• EF Core DB provider
• EF Core tools
 Install EF Core DB Provider
• EF Core allows us to access databases via the provider model.
There are different EF Core DB providers available for the
different databases. These providers are available as NuGet
packages.
• Here, we want to access MS SQL Server database, so we need to
install Microsoft.EntityFrameworkCore.SqlServer NuGet
package.
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Installation
 Install Entity Framework Core
 Install EF Core DB Provider
• To install the DB provider NuGet package, right click on the
project in the Solution Explorer in Visual Studio and select
Manage NuGet Packages.. (or select on the menu: Tools -> NuGet
Package Manager -> Manage NuGet Packages For Solution)
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Installation
 Install Entity Framework Core
 Install EF Core DB Provider
• Notice that the provider NuGet package also installed other
dependent packages such as
Microsoft.EntityFrameworkCore.Relational and
System.Data.SqlClient.
• Alternatively, you can also install provider's NuGet package using
Package Manager Console. Go to Tools -> NuGet Package Manager
-> Package Manager Console and execute the following command
to install SQL Server provider package:
 Install-Package Microsoft.EntityFrameworkCore.SqlServer
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Installation
 Install Entity Framework Core
 Install EF Core Tools
• The command-line interface (CLI) tools for Entity Framework Core
perform design-time development tasks. For example, they create
migrations, apply migrations, and generate code for a model
based on an existing database. The commands are an extension
to the cross-platform dotnet command, which is part of the .NET
Core SDK. These tools work with .NET Core projects.
• EF Tools are available as NuGet packages. You can install NuGet
package for EF tools depending on where you want to execute
commands: using dotnet CLI (Command line interface).
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Installation
 Install Entity Framework Core
 Install EF Core Tools
• The command-line interface (CLI) tools for Entity Framework Core
perform design-time development tasks. For example, they create
migrations, apply migrations, and generate code for a model
based on an existing database. The commands are an extension
to the cross-platform dotnet command, which is part of the .NET
Core SDK. These tools work with .NET Core projects.
• EF Tools are available as NuGet packages. You can install NuGet
package for EF tools depending on where you want to execute
commands: using dotnet CLI (Command line interface).
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Installation
 Install Entity Framework Core
 Install EF Core Tools
• dotnet ef can be installed as either a global or local tool. Most
developers prefer installing dotnet ef as a global tool using the
following command:
 dotnet tool install --global dotnet-ef
• Update the tool using the following command:
 dotnet tool update --global dotnet-ef
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 The DbContext class is an integral part of Entity Framework. An
instance of DbContext represents a session with the database which
can be used to query and save instances of your entities to a
database. DbContext is a combination of the Unit Of Work and
Repository patterns.
 DbContext in EF Core allows us to perform following tasks:
1. Manage database connection
2. Configure model & relationship
3. Querying database
4. Saving data to the database
5. Configure change tracking
6. Caching
7. Transaction management
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 To use DbContext in our application, we need to create the class that
derives from DbContext, also known as context class. This context class
typically includes DbSet<TEntity> properties for each entity in the model.
Consider the following example of context class in EF Core.

public class ApplicationDbContext : DbContext


{
public ApplicationDbContext(DbContextOptions options) : base(options){}
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder){}
protected override void OnModelCreating(ModelBuilder modelBuilder){}
//entities
public DbSet<Student> Students { get; set; }
public DbSet<Classroom> Classrooms { get; set; }
}
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 DbSet
• The DbSet<TEntity> class represents a collection for a given entity
within the model and is the gateway to database operations
against an entity. DbSet<TEntity> classes are added as properties
to the DbContext and are mapped by default to database tables
that take the name of the DbSet<TEntity> property. The DbSet is
an implementation of the Repository pattern

public DbSet<Student> Students { get; set; }


public DbSet<Classroom> Classrooms { get; set; }
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Managing Connection Strings: Connection strings contain
information about the data source that is being connected to. This
information varies from provider to provider, but will usually
include the name and location of the source, and optionally some
means of authenticating the user. The information is provided as
key/value pairs, separated by semi-colons (“;”).
• Configuring The Connection String:
 Overriding The OnConfiguring Method:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)


{
   
optionsBuilder.UseSqlServer("server=.;database=myDb;trusted_connection=true;");
}
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Managing Connection Strings:
• Configuring The Connection String:
 Configuring As A Service

builder.Services.AddDbContext<ApplicationDbContext>(options => {
    options.UseSqlServer("Data Source=.\\SQLEXPRESS;Initial Catalog=DemoManagerStudent;Integrated
Security=True;”});
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Managing Connection Strings:
• Storing Connection Strings: You may prefer to keep your
connection strings in configuration files, so that you can change
them without needing to recompile the application, or use the
features that allow different configuration settings to be used
based on the environment.
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Managing Connection Strings:
• Use the Configuration API to pass the connection string to the
DbContext in the Programs class:

services.AddDbContext<ApplicationDbContext>(options => {
   
options.UseSqlServer(builder.Configuration.GetConnectionString("MyConnection"));
});
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Basic operations
• DbSet objects represent collections of entities in memory. Any
changes you make to the contents of a DbSet will only be
committed to the database if the SaveChanges method of the
DbContext is called.
• The DbSet class exposes a number of methods that enable you to
perform basic CRUD (Create, Read, Update, Delete) operations
against entities.
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Basic operations
• Adding an entity: To add an new entity to the collection represented
by the DbSet, you use the DbSet.Add method
var student = new Student
{
    FirstName = "A",
    LastName = "Nguyen Van"
};
using (var context = new ApplicationDbContext())
{
    context.Students.Add(student); // adds the student to the DbSet in memory
    context.SaveChanges(); // commits the changes to the database
}
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Basic operations
• Retrieving an entity: If you wish to retrieve a single instance of an
entity, you can use the First or Single method depending on whether
you expect there to be more than one row matching the criteria. The
Single method will result in an exception being raised if more than one
matching row exists. It should only be used when querying the context
for entities by a unique key:
• If you are not certain of retrieving any data based on the criteria you
pass in, you should use the FirstOrDefault or SingleOrDefault
methods, which return null in the event that no rows match the
search criteria:
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Basic operations
• Retrieving an entity:
using (var context = new ApplicationDbContext())
{
    var student = context.Students.Single(a => a.Id == 1);
}
using (var context = new ApplicationDbContext())
{
    var student = context.Students.FirstOrDefault(a => a.LastName == "Nguyen");
}
 Retrieving multiple entities: The most commonly method used to
return multiple entities is the ToList method
using (var context = new ApplicationDbContext())
{
    var student = context.Students.ToList();
}
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Basic operations
• Modifying an entity: To update an entity, make the required changes
to the value of the property or properties and call SaveChanges. The
entity must be tracked by the context to be updated:
using(var context = new ApplicationDbContext())
{
//retrieve the entity
    var student = context.Students,FirstOrDefault(s => s.Id == 1);
    if (student != null)
    {
        student.LastName = "Le Van"; // amend properties
        context.SaveChanges(); // commit the changes
    }
}
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 DbContext
 Basic operations
• Deleting an entity: The DbSet class Remove method is used to delete
an entity. The entity must be tracked by the context to be removed

using(var context = new ApplicationDbContext())


{
// retrieve the entity
   var student = context.Students,FirstOrDefault(s => s.Id == 1);
   if (student != null)
   {
        context.Students.Remove(author);
        context.SaveChanges();
   }
}
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 Model
 An Entity Framework Core model is a conceptual model of an
application's domain. The domain includes all topics relevant to the
problem solving areas of interest to the application users. The
model includes data and can also include behaviour.
 Models are expressed as a collection of classes written in C#. Each
class represents an entity (a.k.a. business object, domain object)
within the application domain.
• Eg: class Student, class Classroom, class StudentClassroom
 When working with Entity Framework Core, it is usual for the model
structure to closely match the schema of the database
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Model, Migration, Fluent API


 Fluent API
 EF Core's Fluent API provides methods for configuring various
aspects of your model write in OnModelCreating method in class
DbContext :
• Model-wide configuration
• Type configuration
• Property configuration
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Migration, Fluent API


 Fluent API
 Configuration: Override the OnModelCreating method and use a
parameter modelBuilder of type ModelBuilder to configure domain
classes
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Migration, Fluent API


 Fluent API
 Configuration:
• The ModelBuilder Fluent API instance is used to configure a
property by calling multiple methods in a chain.
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Migration, Fluent API


 Fluent API
 Configuration:
• Configuration of the entity type to be done in line in the method call rather than
being chained
modelBuilder.Entity<Student>(entity =>
{
    entity.ToTable("Student"); //Option
entity.HasKey(e => e.Id);
    entity.Property(e => e.Id)
        .HasColumnName("Id") //Option
        .ValueGeneratedOnAdd() //identity(1,1)
        .IsRequired(); //required field

    entity.Property(e => e.Name)


        .HasColumnType("nvarchar(50)")
        .IsRequired();

    entity.Property(e => e.Avatar)


        .HasColumnType("nvarchar(256)")
        .IsRequired(false);
});
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Migration, Fluent API


 Fluent API
 Configuration:
• Config relationships (A relationship defines how two entities relate
to each other. In a relational database, this is represented by a
foreign key constraint)

modelBuilder.Entity<StudentClassroom>() //”Class many”


    .HasOne<Student>() //”class one”
    .WithMany()
    .HasForeignKey(p => p.StudentId); //foreign key in “class many”
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 DbContext, Migration, Fluent API


 Migration
 When developing applications, the model is likely to change often as
new requirements come to light. The database needs to be kept in
sync with the model. The migrations feature enables you to make
changes to your model and then propagate those changes to your
database schema.
 Install nuget package Microsoft.EntityFrameworkCore.Design
 Creating a Migration
 dotnet ef migrations add <name of migration>
 Removing A Migration
 dotnet ef migrations remove
 Applying A Migration
 dotnet ef database update
Trường đại học xây dựng Hà Nội
Bộ môn Khoa học Máy tính

 Bài tập
 Sửa lại project quản lý sinh viên
 Tạo migration và update vào database 3 bảng student, classroom và
student classroom
 Thực hiện việc xử lý logic thay vì dùng List chuyển sang sử dụng
DbContext theo hướng dẫn

You might also like