gpt4 book ai didi

c# - Entity Framework Core 2.0 CRUD 最佳实践/自动化

转载 作者:行者123 更新时间:2023-12-03 19:28:38 24 4
gpt4 key购买 nike

EF Core 2.0 中是否有既定的 CRUD 最佳实践?

有没有办法自动为模型生成 CRUD,最好使用这些最佳实践?

举个例子,这是我目前拥有的,但我必须将其复制到其他 20 个实体之类的东西:

[Route("entities")]
public class EntitiesController : Controller
{
private readonly ProjectContext _context;

public EntitiesController(ProjectContext context)
{
_context = context;
}

[HttpPost]
public async Task<IActionResult> Post([FromBody]Entities entity)
{
_context.Add(entity);
return Json(await _context.SaveChangesAsync() >= 1);
}

[HttpGet]
public JsonResult Get(int? entityId)
{
if (entityId == null)
return Json(_context.Entities.Select(x => x));
else
return Json(_context.Entities.FirstOrDefault(x => x.EntityId == entityId));
}

[HttpPut]
public async Task<IActionResult> Put([FromBody]Entities entity)
{
if (entity.EntityId < 1)
return BadRequest();

_context.Entities.Update(entity);
return Json(await _context.SaveChangesAsync() >= 1);
}

[HttpDelete]
public async Task<IActionResult> Delete(int entityId)
{
if (entityId < 1)
return BadRequest();

Entities entity = _context.Entities.Where(x => x.EntityId == entityId).FirstOrDefault();
if (entity == null)
return BadRequest();

_context.Entities.Remove(entity);
return Json(await _context.SaveChangesAsync() >= 1);
}
}

最佳答案

有一个有见地的article in Micorosoft's website 。在本文中,他们定义了一些最佳实践。例如,关于直接使用 DbContext 还是存储库存在争议,他们解决了这个问题,如下所示:

The Entity Framework DbContext class is based on the Unit of Work and Repository patterns, and can be used directly from your code, such as from an ASP.NET Core MVC controller. That is the way you can create the simplest code, as in the CRUD catalog microservice in eShopOnContainers. In cases where you want the simplest code possible, you might want to directly use the DbContext class, as many developers do.

However, implementing custom repositories provides several benefits when implementing more complex microservices or applications. The Unit of Work and Repository patterns are intended to encapsulate the infrastructure persistence layer so it is decoupled from the application and domain model layers. Implementing these patterns can facilitate the use of mock repositories simulating access to the database.

因此,作为第一步,您可能应该更改使用 Dbcontext 的方式并使用存储库来代替。本文还有更多要点和提示。

关于c# - Entity Framework Core 2.0 CRUD 最佳实践/自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47925066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com