asp.net core 2.1 dotnet (二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiajing13579/article/details/82834345

调用  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)

{

}

}

}

代码如下:

https://download.csdn.net/download/xiajing13579/10685205

猜你喜欢

转载自blog.csdn.net/xiajing13579/article/details/82834345