概述
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测试接口
最后
以上就是碧蓝蜻蜓为你收集整理的.net Core Api开发的全部内容,希望文章能够帮你解决.net Core Api开发所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复