[原创]MVC引入SqlLiet数据库
引入SQL数据库组件
· 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数据库生成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)
在包管理命令中执行:Add-Migration Init
重新访问地址: https://localhost:7202/posts
