.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測試接口

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章