asp.net core6实现增删改查功能
时间: 2023-07-12 18:26:23 浏览: 173
ASP.NET增删改查操作
ASP.NET Core 6 提供了许多方式来实现增删改查功能,其中最常见的方式是使用控制器(Controller)和数据访问对象(Data Access Object,DAO)。
下面是一个简单的示例,演示如何使用 ASP.NET Core 6 实现增删改查功能:
1. 创建一个 ASP.NET Core 6 Web 应用程序。
2. 在项目中添加一个控制器(Controller),例如,命名为 StudentController:
```csharp
[ApiController]
[Route("[controller]")]
public class StudentController : ControllerBase
{
private readonly IStudentDao _studentDao;
public StudentController(IStudentDao studentDao)
{
_studentDao = studentDao;
}
[HttpGet]
public IActionResult Get()
{
var students = _studentDao.GetAll();
return Ok(students);
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var student = _studentDao.GetById(id);
if (student == null)
{
return NotFound();
}
return Ok(student);
}
[HttpPost]
public IActionResult Create(Student student)
{
_studentDao.Create(student);
return CreatedAtAction(nameof(GetById), new { id = student.Id }, student);
}
[HttpPut("{id}")]
public IActionResult Update(int id, Student student)
{
var existingStudent = _studentDao.GetById(id);
if (existingStudent == null)
{
return NotFound();
}
_studentDao.Update(student);
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var existingStudent = _studentDao.GetById(id);
if (existingStudent == null)
{
return NotFound();
}
_studentDao.Delete(existingStudent);
return NoContent();
}
}
```
3. 创建一个数据访问对象(Data Access Object,DAO),例如,命名为 StudentDao:
```csharp
public interface IStudentDao
{
List<Student> GetAll();
Student GetById(int id);
void Create(Student student);
void Update(Student student);
void Delete(Student student);
}
public class StudentDao : IStudentDao
{
private readonly List<Student> _students = new List<Student>();
public StudentDao()
{
_students.Add(new Student { Id = 1, Name = "张三", Age = 18 });
_students.Add(new Student { Id = 2, Name = "李四", Age = 19 });
_students.Add(new Student { Id = 3, Name = "王五", Age = 20 });
}
public List<Student> GetAll()
{
return _students;
}
public Student GetById(int id)
{
return _students.FirstOrDefault(s => s.Id == id);
}
public void Create(Student student)
{
student.Id = _students.Max(s => s.Id) + 1;
_students.Add(student);
}
public void Update(Student student)
{
var existingStudent = GetById(student.Id);
existingStudent.Name = student.Name;
existingStudent.Age = student.Age;
}
public void Delete(Student student)
{
_students.Remove(student);
}
}
```
4. 在 Startup.cs 文件中注册数据访问对象(Data Access Object,DAO):
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<IStudentDao, StudentDao>();
}
```
至此,您就可以使用上述代码实现 ASP.NET Core 6 中的增删改查功能了。
阅读全文