So sánh entity framework core và ado net

EF Core là framework (thư viện khung) để ánh xạ các đơn vị dữ liệu mô tả bằng lớp (đối tượng) vào cơ sở dữ liệu quan hệ, nó cho phép ánh xạ vào các bảng CSDL, tạo CSDL, truy vấn với LINQ, tạo và cập nhật vào database.

Để sử dụng

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 2 hãy thêm những package cần thiết vào, chạy các lệnh sau:

dotnet add package System.Data.SqlClient dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Design dotnet add package Microsoft.Extensions.DependencyInjection dotnet add package Microsoft.Extensions.Logging dotnet add package Microsoft.Extensions.Logging.Console Những namespace có thể dùng:

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

Tạo Model đơn giản, ánh xạ bảng CSDL

Model là mô hình hóa các đối tượng dữ liệu trong hệ quản trị CSDL thành các đối tượng lập trình, đó là các lớp (class) tương ứng với các bảng ... Hãy tạo ra một dự án

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 3 trong thư mục

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 4 có cài đặt các package trên để thực hành. Ở đây tạo ra một model đơn giản, lớp có tên

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 5 biểu diễn các dòng trong bảng của CDSL, bảng này tên là

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 6

Trước tiên, lớp này định nghĩa thuần túy gồm các thuộc tính như sau:

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} Trước khi sử dụng model

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 5 trong EF Core, hãy bổ sung các thiết lập thông qua các Attribute (sử dụng Sử dụng Attribute) như sau:

  • Thiết lập lớp Product là ánh xạ bảng Products, dùng thuộc tính Table để thiết lập: using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {
    public class Product  
    {  
        public int ProductId {set; get;}  
        public string Name {set; get;}  
        public string Provider {set; get;}  
    }  
    
    } 8
  • Trường using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {
    public class Product  
    {  
        public int ProductId {set; get;}  
        public string Name {set; get;}  
        public string Provider {set; get;}  
    }  
    
    } 9 là của bảng với thuộc tính using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {
    [Table("Products")]  
    public class Product  
    {  
        [Key]  
        public int ProductId {set; get;}  
        [Required]  
        [StringLength(50)]  
        public string Name {set; get;}  
        [StringLength(50)]  
        public string Provider {set; get;}  
    }  
    
    } 0
  • Trường using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {
    [Table("Products")]  
    public class Product  
    {  
        [Key]  
        public int ProductId {set; get;}  
        [Required]  
        [StringLength(50)]  
        public string Name {set; get;}  
        [StringLength(50)]  
        public string Provider {set; get;}  
    }  
    
    } 1 bắt buộc phải thiết lập (khác null) dùng thuộc tính using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {
    [Table("Products")]  
    public class Product  
    {  
        [Key]  
        public int ProductId {set; get;}  
        [Required]  
        [StringLength(50)]  
        public string Name {set; get;}  
        [StringLength(50)]  
        public string Provider {set; get;}  
    }  
    
    } 2, và độ dài tối là là 50 ký tự với thuộc tính using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {
    [Table("Products")]  
    public class Product  
    {  
        [Key]  
        public int ProductId {set; get;}  
        [Required]  
        [StringLength(50)]  
        public string Name {set; get;}  
        [StringLength(50)]  
        public string Provider {set; get;}  
    }  
    
    } 3

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

Đây là khai báo một lớp bình thường, chỉ có bổ sung thêm vài thuộc tính mô tả (Attribute) cho lớp, thuộc tính - các Attribute này được sử dụng bởi EF.

Tạo Context - DbContext

DbContext trong EF là ngữ cảnh làm việc, nó biểu diễn, chứa các thông tin cần thiết của một phiên làm việc với CSDL.

Để thực hiện tạo ra mối liên hệ bảng Products tong CSDL và model, tạo ra Context như sau: Tạo lớp kế thừa

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

4 đặt tên là

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

5, lớp này mang ý nghĩa như là một CSDL.

Trong đó cần nạp chồng

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

6 để cấu hình (thiết lập chuỗi kết nối ...), và tạo ra thuộc tính có kiểu

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

7 chính là bảng trong CSDL

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} Từ lớp kế thừa

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

4 là

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

5 có thể tương tác với CSDL bằng cách gọi các phương thức thích hợp trong DbContext, tìm hiểu một số trường hợp đơn giản sau đây.

Tạo và xóa Database

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

4 có thuộc tính

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} 1, thuộc tính này là đối tượng kiểu

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} 2, từ đó có thể tạo / xóa database.

EnsureCreatedAsync là phươnng thức của

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} 2 để tạo ra database, nếu database nó đang không tồn tại, nếu DB đã tồn tại thì không làm gì cả.

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} Chạy thử phương thức trong hàm Main

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công Thi hành thì nó sẽ tạo ra database, nếu DB đó chưa có! Database này tạo ra có tên

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} 4, có một bảng tên

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 6 với cấu trúc giống mô tả trong model

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 5

So sánh entity framework core và ado net

DeleteDatabase là phươnng thức của

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} 2 để xóa CSDL.

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} Phương thức

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} 8,

using Microsoft.EntityFrameworkCore; namespace ef01 {

public class ProductsContext : DbContext  
{  
    // Thuộc tính products kiểu DbSet cho biết CSDL có bảng mà  
    // thông tin về bảng dữ liệu biểu diễn bởi model Product  
    public DbSet products {set; get;}
    // Chuỗi kết nối tới CSDL (MS SQL Server)  
    private const string connectionString = @"  
            Data Source=localhost,1433;  
            Initial Catalog=mydata;  
            User ID=SA;Password=Password123";
    // Phương thức OnConfiguring gọi mỗi khi một đối tượng DbContext được tạo  
    // Nạp chồng nó để thiết lập các cấu hình, như thiết lập chuỗi kết nối  
    protected override void  OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
    {  
        base.OnConfiguring(optionsBuilder);  
        optionsBuilder.UseSqlServer(connectionString);  
    }s  
}  
} 9 dùng kỹ thuật

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 0, nếu muốn dùng phiên bản đồng bộ thì là

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 1,

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 2

Chèn dữ liệu vào các bảng, AddAsync, AddRangeAsync, SaveChangesAsync

Các đối tượng

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

4 hay

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 4 (như thuộc tính products của lớp ProductContext ở trên) có phương thức

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 5 để bạn chèn đối tượng phù hợp vào DbContext, nó nhận tham số là đối tượng Model cần chèn vào. Sau đó gọi phương thức

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 6 để thực hiện cập nhật dữ liệu vào Server SQL

// Thực hiện chèn hai dòng dữ liệu vào bảng Product // Dùng AddAsync trong DbSet và trong DbContext public static async Task InsertProduct() {

using (var context = new ProductsContext())  
{  
    // Thêm sản phẩm 1  
    await  context.products.AddAsync(new Product  
    {  
        Name = "Sản phẩm 1",  
        Provider = "Công ty 1"  
    });  
    // Thêm sản phẩm 2  
    await  context.AddAsync(new Product()  
    {  
        Name = "Sản phẩm 2",  
        Provider = "Công ty 1"  
    });
    // Thực hiện cập nhật thay đổi trong DbContext lên Server  
    int rows = await context.SaveChangesAsync();  
    Console.WriteLine($"Đã lưu {rows} sản phẩm");
}  
} Chạy thử:

static async Task Main(string[] args) {

await InsertProduct();  
}
So sánh entity framework core và ado net

Nếu muốn thêm một lúc nhiều dữ liệu thì dùng

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 7, nó có thể nhận đối số là mảng các đối tượng cần chèn vào

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

0

Đọc dữ liệu từ bảng, truy vấn với LINQ

Các đối tượng

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 4 có phương thức

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 9 hay

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 0 để lấy về tất cả các dữ liệu (List) của bảng. Đặc biệt bạn có thể dùng LINQ ( đọc Linq C#) trên các đối tượng này (nguồn là các DbSet)

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

1

So sánh entity framework core và ado net

Cập nhật dữ liệu trong EF

Muốn cập nhật dữ liệu, chỉ việc thay đổi thuộc tính của đối tượng đọc được, sau đó gọi

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 1

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

2

Nếu muốn một đối tượng riêng lẻ, không giám sát - muốn thực hiện cập nhật thì gọi đến phương thức Update của DbSet

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

3

Nếu muốn cập nhật một số trường nào đó, dùng cách cập nhật đối tượng độc lập

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

4

Lưu ý, các đối tượng như Product kết quả truy vấn, hoặc được thêm vào ... thì mặc định là được giám sát - theo dõi bởi EF. Khi những đối tượng này thay đổi trạng thái thì

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 2 sẽ thực hiện các tác vụ dựa theo trạng thái của nó.

Mỗi dòng Product trả về từ truy vấn, hoặc thêm vào thì trong EF có một đối tượng

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 3 tương ứng để để quản lý. Để lấy EntityEntry có thể dùng phương thức Entry, bạn có thể dùng nó để thay đổi trạng thái thủ công, ví dụ để điều chỉnh sự ảnh hưởng khi gọi SaveChange. Ví dụ, loại bỏ không bị giảm sát bởi EF cho đối tượng product nhận được

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

5

Có một số state gồm:

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 4,

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 5,

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 6,

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 7,

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 8

Xóa dữ liệu trong EF

Để xóa dữ liệu khỏi DB, chỉ việc yêu cầu xóa đối tượng khỏi DbContext bằng phương thức

static async Task Main(string[] args) {

await CreateDatabase();  
} // Tạo mydata // CSDL mydata : tạo thành công 9, rồi gọi

// Tạo Database mydata (tên mydata từ thông tin kết nối) // Gồm tất cả các bảng định nghĩa bởi các thuộc tính kiểu DbSet public static async Task CreateDatabase() {

using (var dbcontext = new ProductsContext())  
{  
    String databasename = dbcontext.Database.GetDbConnection().Database;// mydata
    Console.WriteLine("Tạo " + databasename);
    bool result = await dbcontext.Database.EnsureCreatedAsync();  
    string resultstring = result ? "tạo  thành  công" : "đã có trước đó";  
    Console.WriteLine($"CSDL {databasename} : {resultstring}");  
}  
} 6 để cập nhật

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

6

EF Logger hiện thị SQL Query trên terminal

Nếu muốn thật sự các câu truy vấn do EF, Linq sinh ra để tương tác với Database thì thêm loger như sau, thêm vào lớp ProductContext phương thức SetLogging:

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

7

So sánh entity framework core và ado net
Mã nguồn - Source code

EF Logger trong .Net Core 3.x

Đối với .Net Core 3.x để thiết lập Logger in thông tin tại console thì cần tạo ra một

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} 1, sau đó thiết lập sử dụng nó ở phương thức

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

6 của lớp

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

[Table("Products")]  
public class Product  
{  
    [Key]  
    public int ProductId {set; get;}
    [Required]  
    [StringLength(50)]  
    public string Name {set; get;}
    [StringLength(50)]  
    public string Provider {set; get;}  
}  
}

5

Đầu tiên hãy đảm bảo cài đặt các Package mới nhất:

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

8

Tạo ILoggerFactory như sau:

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks;

9

Mặc định ILoggerFactory này bắt tất cả các sự kiện, nếu muốn thiết lập các category muốn lọc cũng như cấp độ thì gọi thêm phương thức

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} 4 khi tạo

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} 1, ví dụ:

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ef01 {

public class Product  
{  
    public int ProductId {set; get;}  
    public string Name {set; get;}  
    public string Provider {set; get;}  
}  
} 0

Trường hợp trên thiết lập lọc các log thuộc chuyên mục

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} 6 ở mức độ

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} 7 và chuyên mục

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} 8 ở mức độ

public static async Task DeleteDatabase() {

using (var context = new ProductsContext())  
{  
    String databasename = context.Database.GetDbConnection().Database;  
    Console.Write($"Có chắc chắn xóa {databasename} (y) ? ");  
    string input = Console.ReadLine();
    // Hỏi lại cho chắc  
    if (input.ToLower() == "y")  
    {  
        bool deleted = await context.Database.EnsureDeletedAsync();  
        string deletionInfo = deleted ? "đã xóa" : "không xóa được";  
        Console.WriteLine($"{databasename} {deletionInfo}");  
    }  
}
} 9

Các cấp khác xem tại: LogLevel

Các tên category tham khảo đối với EF Logger: DbLoggerCategory.Database.Command, DbLoggerCategory.Database.Connection, DbLoggerCategory.Database.Transaction, DbLoggerCategory.Infrastructure, DbLoggerCategory.Migration, DbLoggerCategory.Model, DbLoggerCategory.Query, DbLoggerCategory.Scaffolding, DbLoggerCategory.Update