asp.net core WebAPI利用内存数据库实现CRUD
2019-04-03 本文已影响0人
JADDC
一、在VS2017中创建名为【CRM】的【ASP.Net Core Web应用程序】

二、在项目中新建Models
文件夹,在此文件夹下面创建上下文(CRMContext)和一个UserInfo类
CRMContext文件里的内容如下
public class CRMContext:DbContext
{
public CRMContext(DbContextOptions<CRMContext> options) : base(options)
{
}
public DbSet<UserInfo> UserInfos { get; set; }
}
UserInfo文件里的内容如下
public int Id { get; set; }
public string UserName { get; set; }
public int Age { get; set; }
public bool IsDeleted { get; set; }
三、创建UserInfoController,并完成在内容中查询和添加功能
UserInfoController文件里的内容如下
//[Route("api/[controller]")]直接使用[controller]也可以读取到UserInfo,但是controller改名,那接口的名字也会改了
[Route("api/userInfo")]
[ApiController]
public class UserInfoController : ControllerBase
{
private readonly CRMContext _context;
public UserInfoController(CRMContext context)
{
_context = context;
if (!_context.UserInfos.Any())
{
_context.UserInfos.Add(new UserInfo() { UserName = "Jason",Age = 18,Id = 1,IsDeleted = false});
_context.UserInfos.Add(new UserInfo() { UserName = "Tom",Age = 23,Id = 2,IsDeleted = false});
_context.SaveChanges();
}
}
[HttpGet]
public IEnumerable<UserInfo> GetAll()
{
return _context.UserInfos.ToList();
}
[HttpGet("{id}", Name = "GetUserInfo")]
public IActionResult GetById(long id)
{
var item = _context.UserInfos.FirstOrDefault(t => t.Id == id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
[HttpPost]
public IActionResult Create([FromBody] UserInfo item)
{
if (item == null)
{
return BadRequest();
}
_context.UserInfos.Add(item);
_context.SaveChanges();
return CreatedAtRoute("GetUserInfo", new { id = item.Id }, item);
}
}
四、在Startup文件中添加Context服务
services.AddDbContext<CRMContext>(opt => opt.UseInMemoryDatabase("CRM"));
Startup文件整体效果

五、其他



