本文將在asp.net core api 項目中使用efcore corefirst模式 簡單配置鏈接sqlserver數據庫,以及簡單的數據庫遷移操作
一 新建項目
1. 首先我們先用vs2017 創建一個空的 asp.net core api 項目
2. 在生成的解決方案下在建立一個訪問數據庫使用的類庫CoreApi.Model,注意要選擇.netcore下的類庫,如圖所示
二 添加相關引用
1. 打開nuget包的程序管理命令控制台,執行添加引用命令 ,注意執行時控制台的默認項目要定位為 CoreApi.Model
引用 EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore
引用 EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.SqlServer
引用 EntityFrameworkCore.SqlServer.Tools
Install-Package Microsoft.EntityFrameworkCore.Tools
三 相關配置
1. 在appsettings.json 文件中添加sqlserver的數據庫鏈接配置,配置如下
{
"ConnectionStrings": {
"SqlServerConnection": "Server=.;Database=dbCore;User ID=sa;Password=abc123456;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
2.修改項目Startup.cs 文件 的ConfigureServices 方法,注意此處必須引用 using Microsoft.EntityFrameworkCore
以及using CoreApi.Model;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var sqlConnection = Configuration.GetConnectionString("SqlServerConnection");
services.AddDbContext<ApiDBContent>(option => option.UseSqlServer(sqlConnection));
services.AddMvc();
}
四 生成數據庫
-
首先在CoreApi.Model下建立在UserInfo 用戶模型
public class UserInfo
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
2. 配置數據上下文
public class ApiDBContent : DbContext
{
public ApiDBContent(DbContextOptions<ApiDBContent> options)
: base(options)
{
}
public DbSet<UserInfo> Users { get; set; }
}
3. 打開程序包管理控制台,執行 Add-Migration Migrations 命令,注意此時默認項目也必須定位CoreApi.Model,
如果順利的話項目下應該會生成一個Migrations的文件夾並包含一些初始化生成數據庫需要用的文件

4.執行 update-database 命令生成數據庫,
五 簡單的數據庫遷移
-
我們新增一個Articles 模型 在userinfo中增加兩個字段,使用命令將其更新至數據庫,還是需要注意默認項目也必須定位CoreApi.Model,因為我們所有的數據庫操作都是針對model層的
public class UserInfo
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Phone { get; set; }
public virtual List<Articles> Articles { get; set; }
}
public class Articles
{
public int Id { get; set; }
public string Title { get; set; }
public string summary { get; set; }
public virtual UserInfo User{get;set;}
}
-
我們執行 命令 Add-Migration migrationName 和 update-datebase 成功后刷新數據庫可以看到表和字段都相應的加上了 ,當然還有外鍵

六 最后我們在數據庫中初始化一些數據 然后使用efcore 請求數據
1. 在數據庫初始用戶數據
2. 構造函數方式初始化數據上下文, 簡單修改ValuesController 下的 Get 方法
private readonly ApiDBContent _dbContext;
public ValuesController(ApiDBContent dbContext)
{
_dbContext = dbContext;
}
// GET api/values
[HttpGet]
public JsonResult Get()
{
return Json(_dbContext.Users.Take(2).ToList()) ;
//return new string[] { "value1", "value2" };
}
3. 啟動項目 請求get api
本文永久更細地址:http://siyouku.cn/article/6818.html

