开发工具 Vs2017 +MSsqlsever

打开VS2017,新建web项目

 

点击确认,生成项目,在项目中增加文件夹Model,在Model中增加类TodoItem

1 public class TodoItem
2     {
3         public long Id { get; set; }
4         public string Name { get; set; }
5         public bool IsComplete { get; set; }
6 
7     }
View Code

在Model中增加类TodoContext,用于与数据库的交互

1  public class TodoContext : DbContext
2     {
3         public TodoContext(DbContextOptions<TodoContext> options)
4             : base(options)
5         {
6         }
7 
8         public DbSet<TodoItem> TodoItems { get; set; }
9     }
View Code

打开appsettings.json,配置数据库连接字符串

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "TodoContext": "Server=.;Database=WebApiDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
  }

}

在Startup中,找到注册服务的方法ConfigureServices中注册数据库上下文,并指定数据库为sqlserver

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<Models.TodoContext>(opt =>
             opt.UseSqlServer(Configuration.GetConnectionString("TodoContext")));  //使用SqlServer数据库

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

至此,基本的配置已经完成,现在用EF的codefirst方式,创建数据库,通过工具-》NuGet包管理器--》程序包管理器控制台 调出控制台

命令如下:

Add-Migration Initial
Update-Database

  现在数据库就已经搭建完毕

 

接下来我们在Control文件夹下增加TodoController 

 [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodoController(TodoContext context)
        {
            _context = context;

            if (_context.TodoItems.Count() == 0)
            {
                // Create a new TodoItem if collection is empty,
                // which means you can't delete all TodoItems.
                _context.TodoItems.Add(new TodoItem { Name = "Item1" });
                _context.SaveChanges();
            }
        }

        // GET: api/Todo
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
        {
            return await _context.TodoItems.ToListAsync();
        }

        // GET: api/Todo/5
        [HttpGet("{id}")]
        public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);

            if (todoItem == null)
            {
                return NotFound();
            }

            return todoItem;
        }
    }

  至此,整个Api项目已经搭建完毕,现在可以验证是否OK

看到调用API,已经成功返回值,接下来一篇我们就聊聊常用的Post和Get,以及传参的事情

posted on 2019-09-07 13:43  中年的危机  阅读(1371)  评论(2编辑  收藏  举报