Article Directory
Sqlite installation and use
Sqlite features
Sqlite is a lightweight database that does not require installation and can be used across platforms. It is the optimal solution for small software, small projects, and rapid transplantation. There is no need to install the database first like mysql and Sqlserver, and then use it.
Environment installation
Net.Core =6.0
project files
- EF.Sqlite: Sqlite lightweight database, no need to install, only need to import Nuget package
- EF.Tool: Database transfer tool, .Net defaults to Sqlserver. This is to transfer database management objects from Sqlserver to sqlite
- EF framework introduction
What are EFs?
EF is an ORM entity-relationship database, what is ORM? Simply put, ORM means that the objects that our program runs are consistent with the objects stored in the database. The database is just one place where the data we run is persisted. A database is simply a large, persistent array of objects.
example
EF uses
Create two new files
- DbContext.cs: database corresponding class, used for sql operation
- DtName.cs: The corresponding class of the data table, used to design the corresponding fields of the data table, Id does not need
example
Database: MyToDoDbContext, inherited from DbContext
using Microsoft.EntityFrameworkCore;
namespace MyToDo.Api.Context
{
public class MyToDoContext:DbContext
{
public MyToDoContext(DbContextOptions<MyToDoContext> options):base(options)
{
//继承DbContext建库方法
}
public DbSet<ToDo> ToDo {
get; set; }
}
}
Data table corresponding entity: ToDo class
namespace MyToDo.Api.Context
{
public class ToDo
{
public string Title {
get; set; }
public string Content {
get; set; }
public int Status {
get; set; }
}
}
Add database connection string in json
{
"ConnectionStrings": {
"ToDoConnection": "Data Source=to.do"
},
...
}
Set in Program, refer to sqlite
builder.Services.AddDbContext<MyToDoContext>(options =>
{
//这个是我们在appsettings.json里面添加的数据库连接串
var connectionStr = builder.Configuration.GetConnectionString("ToDoConnection");
options.UseSqlite(connectionStr);
});
Nuget console
Nuget management tool default project selection WebApi project
We enter the code in the console: Add-Migration MyToDo (your manager name)
Then enter Update-Database
If you report this error, remember to check if your configuration name is correct
We have created a new database here, that is, the creation is successful