本文将在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的数据库链接配置,配置如下
class="brush:js;toolbar:false">{
"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 成功后刷新数据库可以看到表和字段都相应的加上了 ,当然还有外键

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://www.siyouku.cn
本文永久更细地址:http://siyouku.cn/article/6818.html