asp.net core 2.1 dotnet (二)
呼叫 ET 的方式
新建 APPDbContext 這樣一個檔案:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using CoreAPI.Mdoel;
namespace CoreAPI
{
public class APPDbContext:DbContext
{
public APPDbContext(DbContextOptions<APPDbContext> options):base(options)
{
}
public DbSet<User> User { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
由於 在 .net core 中使用 註冊的方式,不需要 new() 一個類,直接傳入就可以了。
在 其中一 個 control中 測試的例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft;
namespace CoreAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
APPDbContext _context;
public ValuesController(APPDbContext context){
this._context = context;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
CoreAPI.Mdoel.User user = new CoreAPI.Mdoel.User();
user.UserName = "tesd2";
user.Password = "password";
_context.Add(user);
_context.SaveChanges();
// 這裡不能直接用 single得到,否則會出錯。
var v1 = _context.User.Where(c=>c.Id==2);
return v1.Take(1).Single().UserName + v1.Take(1).Single().Password;
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}