C# 清理代码问题:EF核心参数化要包括哪些属性
这个问题是关于干净的代码和最佳实践的。我们正在使用.NET Core 3.1来开发一个web应用程序。假设我们有一个接受请求的C# 清理代码问题:EF核心参数化要包括哪些属性,c#,entity-framework,asp.net-core,C#,Entity Framework,Asp.net Core,这个问题是关于干净的代码和最佳实践的。我们正在使用.NET Core 3.1来开发一个web应用程序。假设我们有一个接受请求的PostsController,PostService从数据库返回一些数据,以及带有一些属性的Post数据库模型 public class PostsController : Controller { private readonly IPostsService _postsService; public PostsController(IPostsSe
PostsController
,PostService
从数据库返回一些数据,以及带有一些属性的Post
数据库模型
public class PostsController : Controller
{
private readonly IPostsService _postsService;
public PostsController(IPostsService postsService)
{
_postsService = postsService;
}
public IActionResult Get(int id)
{
Post post = _postsService.Get(id);
return View(post);
}
}
public class PostsService : IPostsService
{
private readonly MyDbContext _dbContext;
public PostsService(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public Post Get(int id)
{
return _dbContext.Post
.Include(x => x.FirstPropery)
.FirstOrDefault(x => x.Id == id);
}
}
一切都好吧?但假设有另一个控制器(或另一个服务,其实并不重要)也调用\u postsService.Get(id)
,但它不需要Post
,只需FirstProperty
。它还需要它的secondproperty
。因此,其适当的服务功能应为:
public Post Get(int id)
{
return _dbContext.Post
.Include(x => x.FirstPropery)
.Include(x => x.SecondPropery)
.FirstOrDefault(x => x.Id == id);
}
想象一下,可能有n
控制器都需要通过其Id
进行Post,但每个控制器都需要自己包含的属性
public class PostsController : Controller
{
private readonly IPostsService _postsService;
public PostsController(IPostsService postsService)
{
_postsService = postsService;
}
public IActionResult Get(int id)
{
Post post = _postsService.Get(id);
return View(post);
}
}
public class PostsService : IPostsService
{
private readonly MyDbContext _dbContext;
public PostsService(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public Post Get(int id)
{
return _dbContext.Post
.Include(x => x.FirstPropery)
.FirstOrDefault(x => x.Id == id);
}
}
在这种情况下我们该怎么办
n
不同的服务方法,每个方法返回的帖子包含不同的属性?丑陋的所有属性的常规维修方法?丑陋,缓慢,许多属性是不需要的
包含的s?我不想硬编码任何字符串属性,因为它会导致许多错误。我需要一个干净的解决方案,如果我们在Post
模型中更改某个属性的名称,它将产生编译时错误
想象一下,可能有n个控制器都需要按其Id进行Post,但每个控制器都需要自己包含的属性
public class PostsController : Controller
{
private readonly IPostsService _postsService;
public PostsController(IPostsService postsService)
{
_postsService = postsService;
}
public IActionResult Get(int id)
{
Post post = _postsService.Get(id);
return View(post);
}
}
public class PostsService : IPostsService
{
private readonly MyDbContext _dbContext;
public PostsService(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public Post Get(int id)
{
return _dbContext.Post
.Include(x => x.FirstPropery)
.FirstOrDefault(x => x.Id == id);
}
}
这就是为什么您的控制器应该可以访问IQueryable
。这是允许控制器指定查询的类型。您建议的替代方案只是一个非常有限的、自行开发的API,用于让控制器控制查询