[原創(chuàng)]MVC引入SqlLiet數(shù)據(jù)庫
引入SQL數(shù)據(jù)庫組件
· Microsoft.EntityFrameworkCore.Sqlite
·
官方參考鏈接:https://docs.microsoft.com/zh-cn/ef/core/providers/sqlite/?tabs=dotnet-core-cli
SQLLITE連接字符串:https://docs.microsoft.com/zh-cn/dotnet/standard/data/sqlite/connection-strings
添加測試模型,生成基架
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
}
默認用SQLSERVER數(shù)據(jù)庫生成appsetting.json
"ConnectionStrings": {
//"db": "Server=(localdb)\\mssqllocaldb;Database=SqlLiteMVC.Data;Trusted_Connection=True;MultipleActiveResultSets=true",
"db": "Data Source=mydb.db;Cache=Shared;Default Timeout=30"
}
將sqlserver替換成sqllite連接字符串,同時把program.cs中的也換過來,如下:
builder.Services.AddDbContext<db>(options =>
//options.UseSqlServer(builder.Configuration.GetConnectionString("db") ?? throw new InvalidOperationException("Connection string 'db' not found.")));
options.UseSqlite(builder.Configuration.GetConnectionString("db") ?? throw new InvalidOperationException("Connection string 'db' not found.")));
訪問地址:https://localhost:7202/posts
報如下錯誤:
An unhandled exception occurred while processing the request.
SqliteException: SQLite Error 1: 'no such table: Post'.
Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(int rc, sqlite3 db)
在包管理命令中執(zhí)行:Add-Migration Init
重新訪問地址: https://localhost:7202/posts
