.net Core Api开发

sqlserver数据库

.net Core2.1 

1、创建.netcore项目 NetCoreApiData

2、创建数据库MoviesDemo

3、修改项目数据库连接

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MoviesDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

4、创建Model类:Student

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

namespace NetCoreApiMongo.Models
{
    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Sex { get; set; }

        public int Age { get; set; }

        public string Dept { get; set; }

        public decimal Score { get; set; }
    }
}
 

5、创建类CoreDbContext

using Microsoft.EntityFrameworkCore;
using NetCoreApiData.Models;
using NetCoreApiMongo.Models;
using NetCoreApiMongo.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetCoreApiData.Data
{
    public class CoreDbContext:DbContext
    {
      public virtual DbSet<Student> Students { get; set; }

      public CoreDbContext(DbContextOptions<CoreDbContext> options):base(options)
      {
       
      }

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    if (!optionsBuilder.IsConfigured)
        //    {
        //        optionsBuilder.UseSqlServer(ConfigModel.ConnectionStrings);
        //    }
        //}
    }
}
 

6、创建控制器类MyControllerBaseController,如果是多个控制器需要创建一个基控制器类,其他的继承于它

 

namespace NetCoreApiData.Controllers
{
    [ApiController]
    public class MyControllerBaseController: ControllerBase
    {
     
    }
}

7、创建数据库控制器类StudentController

 

namespace NetCoreApiMongo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : MyControllerBaseController
    {

        private CoreDbContext _coreDbContext;

        public StudentController(CoreDbContext coreDb)
        {
            _coreDbContext = coreDb;
            if (_coreDbContext.Students.Count() == 0)
            {
                _coreDbContext.Students.Add(new Student
                {
                    Name = "sunya",
                    Sex = "女",
                    Age = 30,
                    Dept = "计算机科学与技术",
                    Score = 100
                });
            }
        }

        // GET api/values
        [HttpGet]
        public List<Student> Get()
        {
            return _coreDbContext.Set<Student>().ToList();
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public Student Get(int id)
        {
            Student stu = _coreDbContext.Set<Student>().ToList().FirstOrDefault(f => f.Id == id);
            return stu;
        }

        // POST api/values
        [HttpPost]
        public async Task<ActionResult<Student>> Post(Student value)
        {
            if (_coreDbContext.Students.Where(f => f.Id == value.Id) != null)
            {
                return BadRequest();
            }
            _coreDbContext.Students.Add(value);
            await _coreDbContext.SaveChangesAsync();
            return CreatedAtAction(nameof(Get), new { id = value.Id });
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public async Task<ActionResult<Student>> Put(int id, Student item)
        {
            if (id != item.Id)
            {
                return BadRequest();
            }
            _coreDbContext.Entry(item).State = EntityState.Modified;
            await _coreDbContext.SaveChangesAsync();

            return CreatedAtAction(nameof(Get), new { id = item.Id });
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<Student>> Delete(int id)
        {
            var ss = _coreDbContext.Set<Student>().ToList().FirstOrDefault(f => f.Id == id);

            _coreDbContext.Students.Remove(ss);
            await _coreDbContext.SaveChangesAsync();
            return CreatedAtAction(nameof(Get), new { id = id });
        }
    }
}
 

 

8、创建配置类ConfigModel,用于数据库连接使用

    public static class ConfigModel
    {
      public static string ConnectionStrings { get; set; }


    }

9、修改Startup类 方法

  public void ConfigureServices(IServiceCollection services)
        {
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies 
            //    // is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});
            ConfigModel.ConnectionStrings = Configuration["ConnectionStrings:DefaultConnection"];
            services.AddMvc();
            services.AddDbContext<CoreDbContext>(option =>
            {
                var connectionString = ConfigModel.ConnectionStrings;
                option.UseSqlServer(connectionString);
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        }

 

10、启动项目,使用postman测试接口

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值