You are on page 1of 3

Chỉ được sửa trong OnConfuguring

WEB: chỉnh cổng chạy yêu cầu trong properties => launchSettings

3.On Developer PowerShell dialog , execute the following commands to generate model:

dotnet ef dbcontext scaffold "server =(local); database = MyStore;uid=sa;pwd=123;"


Microsoft.EntityFrameworkCore.SqlServer --output-dir Models

-appsettings.json

{
"ConnectionStrings": {
"PE_Fall21B5DB":
"Server=(local);uid=sa;pwd=123;database=PE_Fall21B5;Trusted_Connection=True;TrustServerCertificate=True"
}
}

-Dbcontext.cs

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)


{
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
optionsBuilder.UseSqlServer(config.GetConnectionString("PE_Fall21B5DB"));
}

 Với Windows Forms App

Trường hợp bạn khai thác dữ liệu từ database bằng EF (Entity Framework)
Microsoft.entityframeworkcore.design(6.0.1)

Microsoft.entityframeworkcore.sqlserver(6.0.1)

Microsoft.extensions.configuration.json(6.0.0)

Trường hợp bạn khai thác dữ liệu từ database bằng ADO.NET


Microsoft.extensions.configuration.json(6.0.0)

System.data.sqlclient(4.8.3)

 Với ASP.NET Core Web App ( Nó có sẵn thư viện json rồi ) :

Trường hợp bạn khai thác dữ liệu từ database bằng EF (Entity Framework)
Microsoft.entityframeworkcore.design(6.0.1)

Microsoft.entityframeworkcore.sqlserver(6.0.1)

Trường hợp bạn khai thác dữ liệu từ database bằng ADO.NET


System.data.sqlclient(4.8.3)
 Đến Menu
 Câu lệnh gen folder Modes sử dụng cho Entity Framework:
dotnet ef dbcontext scaffold "server =localhost; database =
Project3_SE1631;uid=sa;pwd=123;" Microsoft.EntityFrameworkCore.SqlServer --output-dir
Models
hoặc dùng câu lệch này :

dotnet ef dbcontext scaffold "server =(local); database =


PE_PRN211_22FallB5;uid=sa;pwd=123;TrustServerCertificate=true"
Microsoft.EntityFrameworkCore.SqlServer --output-dir Models

 Đoạn code đọc file json trong hàm onconfig: ( với Entity Framework nhớ thay vào
hàm đc dạy trong class có đuôi Context.cs )

var config = new


ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
optionsBuilder.UseSqlServer(config.GetConnectionString("MyCnn"));

-Text trong appsettings.json :

{
"ConnectionStrings": {
"MyCnn": "server=localhost;database=MyDB2;uid=sa;pwd=123"
}
}

Với câu Q2 PE nên dùng

{
"ConnectionStrings": {

"MyCnn":"server=(local);database=MySaleDB;uid=sa;pwd=123;TrustServerCertificate=true"
}
}

Tiện ích riêng cho EF


 Đến Menu

 Lấy danh sách Course :

List<Course> course = _context.Courses.Include(x => x.Subject).Include(x =>


x.Instructor).Include(x => x.Subject)
.Include(x => x.Term).Include(x => x.Campus).ToList();
course = course.Where(x => x.CourseCode.Equals(search)).ToList();

You might also like