【发布时间】:2019-01-15 15:58:55
【问题描述】:
我试图返回一个对象列表,但只包含该对象的一个属性的子集。
控制器
[ServiceFilter(typeof(LogUserActivity))]
public class CabinsController : Controller
{
private readonly IBaseRepository _repo;
public CabinsController(IBaseRepository repo)
{
_repo = repo;
}
public IActionResult GetCabins()
{
return Ok(_repo.GetCabins());
// upon completing the action, the LogUserActivity
// filter saves changes to the database.
}
}
存储库
public List<Cabin> GetCabins()
{
// retrieve list of all cabins
var cabins = _context.Cabins.ToList();
// only show current occupants of the cabins
foreach (var cabin in cabins) {
cabin.occupants =
cabin.occupants.Where(o =>
o.StartDate <= DateTime.UtcNow &&
o.EndDate >= DateTime.UtcNow).ToList();
}
return cabins;
}
但是,这会改变_context 和它所连接的数据库。它正在删除所有不是最新的occupants。
如何在不更改数据源的情况下检索对象属性的子集?
【问题讨论】:
-
如果要修改实体模型,请不要使用它们。使用与实体完全不同的 DTO。
-
您的要求不明确!请告诉我您希望从
GetCabins()方法中获得哪些过滤数据,以及为什么在GetCabins()中使用foreach -
@DavidG 我确实有 DTO。所以,你的意思是我应该在数据转换为 DTO 后更改数据?
-
@DavidG 你的建议非常有效。
标签: c# entity-framework asp.net-core-2.2