单个数据库调用从EF Core中的多个表中提取数据

时间:2016-06-27 20:12:32

标签: entity-framework entity-framework-core

以下代码当前为我的数据库打开了三次连接,以拉出每个对象。

有没有更好的方法来制作查询,因此数据库只被击中一次并拉回我正在寻找的所有对象?

var metadataResult = new MetadataViewModel
            {
                Milestones = goalsContext.Milestones.Select(m => new MilestoneViewModel
                {
                    Id = m.Id,
                    Name = m.Name,
                    Year = m.Year,
                    Date = m.Date
                }),
                Aggregates = goalsContext.Aggregates.Select(a => new AggregateViewModel
                {
                    Id = a.Id,
                    Name = a.Name
                }),
                Metrics = goalsContext.Metrics.Select(m => new MetricViewModel
                {
                    Id = m.Id,
                    Name = m.Name,
                    Description = m.Description
                })
            };

1 个答案:

答案 0 :(得分:4)

如果您的视图模型形状非常相似,那么您应该能够使用Union在一个查询中获取所有内容,然后将行转换为适当的ViewModel实例。类似于以下内容 -

var combinedResults =
    context.Products.Select(p => new
    {
        Type = "Product",
        ID = p.ProductID,
        Name = p.ProductName,
        SupplierName = p.Supplier.CompanyName
    })
    .Union(
        context.Categories.Select(c => new
        {
            Type = "Category",
            ID = c.CategoryID,
            Name = c.CategoryName,
            SupplierName = (string)null
        })
    )
    .ToList();

var viewModel = new ViewModel
{
    Products = combinedResults
        .Where(x => x.Type == "Product")
        .Select(x => new ProductViewModel
        {
            ID = x.ID,
            Name = x.Name,
            SupplierName = x.SupplierName
        }),
    Categories = combinedResults
        .Where(x => x.Type == "Category")
        .Select(x => new CategoryViewModel
        {
            ID = x.ID,
            Name = x.Name
        })
};