【问题标题】:ASP.NET Core 2.2 Entity Framework: Get subset of data without altering contextASP.NET Core 2.2 Entity Framework:在不改变上下文的情况下获取数据子集
【发布时间】: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


【解决方案1】:

在小屋对象上使用 .toList() 将创建一个副本以供循环使用:

 foreach (var cabin in cabins.toList()) {

更多信息请参见ToList()-- Does it Create a New List?

【讨论】:

    【解决方案2】:

    分配后

    var cabins = _context.Cabins.ToList();
    

    您在 _context 数据对象中分配新的占用者。以后,如果你写

    _context.SaveChanges();
    

    它节省了数据库。试试这个

    public List<Cabin> GetCabins() 
    {
        // retrieve list of all cabins
        var cabins = _context.Cabins.ToList();
        List<Cabins> cabintemp= new List<Cabins>();
    
        // only show current occupants of the cabins
        cabintemp.occupants=cabins.occupants.Where(o => 
                    o.StartDate <= DateTime.UtcNow && 
                    o.EndDate >= DateTime.UtcNow)
    
        }
    
        return cabintemp;
    }
    

    使用小屋温度。

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 1970-01-01
      • 2020-10-14
      • 2021-08-23
      • 2020-08-11
      • 1970-01-01
      • 2018-03-19
      • 2016-09-17
      • 2017-08-04
      相关资源
      最近更新 更多