asp.net EFcore配置链接sqlserver

时间:2023-03-09 20:15:51
asp.net EFcore配置链接sqlserver

1. 首先我们先用vs2017 创建一个空的 asp.net core api 项目

asp.net EFcore配置链接sqlserver

2.  在生成的解决方案下在建立一个访问数据库使用的类库CoreApi.Model,注意要选择.netcore下的类库,如图所示

asp.net EFcore配置链接sqlserver

二 添加相关引用

1. 打开nuget包的程序管理命令控制台,执行添加引用命令 ,注意执行时控制台的默认项目要定位为 CoreApi.Model

引用 EntityFrameworkCore

Install-Package Microsoft.EntityFrameworkCore

引用 EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.SqlServer

引用 EntityFrameworkCore.SqlServer.Tools

Install-Package Microsoft.EntityFrameworkCore.Tools

asp.net EFcore配置链接sqlserver

三 相关配置

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;

 public void ConfigureServices(IServiceCollection services)
{
var sqlConnection = Configuration.GetConnectionString("SqlServerConnection");
services.AddDbContext<ApiDBContent>(option => option.UseSqlServer(sqlConnection));
services.AddMvc();
}

四 生成数据库

  1. 首先在CoreApi.Model下建立在UserInfo 用户模型  

  2. public  class UserInfo
    {
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    }

    配置数据上下文

  3. public class ApiDBContent : DbContext
    {
    public ApiDBContent(DbContextOptions<ApiDBContent> options)
    : base(options)
    {
    }
    public DbSet<UserInfo> Users { get; set; }
    }

    打开程序包管理控制台,执行 Add-Migration Migrations 命令,注意此时默认项目也必须定位CoreApi.Model,

如果顺利的话项目下应该会生成一个Migrations的文件夹并包含一些初始化生成数据库需要用的文件

asp.net EFcore配置链接sqlserver

asp.net EFcore配置链接sqlserver

4.执行 update-database 命令生成数据库,

asp.net EFcore配置链接sqlserver

五 简单的数据库迁移

  1. 我们新增一个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;} }
  1. 我们执行 命令 Add-Migration migrationName 和 update-datebase   成功后刷新数据库可以看到表和字段都相应的加上了 ,当然还有外键

asp.net EFcore配置链接sqlserver

六 最后我们在数据库中初始化一些数据 然后使用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().ToList()) ;
//return new string[] { "value1", "value2" };
}

3.  启动项目 请求get api

asp.net EFcore配置链接sqlserver

原文地址:http://siyouku.cn/article/6818.html