EF core code First

一,代码先行方案

1.引用Entity Framework Core

在NuGet命令行下安装引用:

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

2.创建实体

在项目中新建Models文件夹,文件夹中新建类User.cs

namespace EfCoreDemo.Models
{
    public class EFUser
    {
        public int Id { get; set; }
        public string UserName { get; set; }

        public string PassWord { get; set; }
    }
}

3.创建操作数据库的上下文DataContext,继承DbContext

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EfCoreDemo.Models
{
    public class DataContext:DbContext
    {
        public DataContext(DbContextOptions options) : base(options)
        {

        }
        public DbSet efnewusers { get; set; }  //对应EFUser 新建数据库efnewusers
    }
}

4.创建数据库

打开Startup.cs,在ConfigureServices添加数据库连接

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(config =>
            {
                config.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddControllers();
        }

在appsettings.json配置数据库链接

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=10.8.59.251;Initial Catalog=Dagdb;uid=sa;pwd=gis1a6b7c!Z"
  }
}

5.添加迁移与创建数据库

Add-Migration Init
Update-Database

6.项目使用数据

在Controller文件夹上,新建API控制器UserController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EfCoreDemo.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace EfCoreDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private DataContext dataContext;
        public UserController(DataContext context)
        {
            dataContext = context;
        }

        [HttpGet]
        public ActionResult> GetAuthors()
        {
            return dataContext.efnewusers.ToList();
        }
    }
}

你可能感兴趣的:(EF core code First)