在 .NET Core 中实现接口的增删改查(CRUD)操作通常涉及创建一个数据访问层(DAL)和一个业务逻辑层(BLL)。这里是一个简单的示例,展示如何使用 Entity Framework Core 和 ASP.NET Core 实现这些操作。
1. 创建项目
首先,使用 .NET CLI 创建一个新的 ASP.NET Core Web API 项目:
dotnet new webapi -n CrudApi
cd CrudApi
2. 安装必要的包
安装 Entity Framework Core 和 SQLite(或其他数据库提供程序):
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
3. 创建数据模型
在 Models 文件夹中创建一个数据模型,例如 Product:
// Models/Product.cs
namespace CrudApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
4. 创建数据库上下文
在 Data 文件夹中创建一个数据库上下文类:
// Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using CrudApi.Models;
namespace CrudApi.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
5. 配置数据库连接
在 appsettings.json 中添加数据库连接字符串:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CrudDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
6. 配置服务
在 Startup.cs 中配置数据库上下文和迁移:
// Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
7. 创建控制器
在 Controllers 文件夹中创建一个控制器来处理 CRUD 操作:
// Controllers/ProductController.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using CrudApi.Data;
using CrudApi.Models;
namespace CrudApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/Product
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
// GET: api/Product/5
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return product;
}
// PUT: api/Product/5
// To protect from overposting attacks, enable the specific properties you want to bind to, use try-catch to handle exceptions.
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct(int id, Product product)
{
if (id != product.Id)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Product
// To protect from overposting attacks, enable the specific properties you want to bind to, use try-catch to handle exceptions.
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// DELETE: api/Product/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return NoContent();
}
private bool ProductExists(int id)
{
return _context.Products.Any(e => e.Id == id);
}
}
}
8. 运行迁移和更新数据库
在终端中运行以下命令来创建和更新数据库:
dotnet ef migrations add InitialCreate
dotnet ef database update
9. 运行应用程序
最后,运行应用程序:
dotnet run
现在,你应该能够通过 https://localhost:5001/api/product 访问你的 CRUD API。
总结
这是一个基本的示例,展示了如何在 .NET Core 中使用 Entity Framework Core 和 ASP.NET Core 实现接口的增删改查操作。你可以根据需要扩展这个示例,例如添加数据验证、错误处理、分页和排序等功能。
1688

被折叠的 条评论
为什么被折叠?



