2016-06-27 43 views
0

下面的代码当前打开三次到我的数据库的连接,以提取每个对象。单个数据库调用从EF 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 
       }) 
      }; 
+0

简答:没有。在EF6中,您可以使用EntityFramework.Extended的未来查询来完成。 –

+0

我不是一位SQL数据库专家,但是我的API调用看起来效率非常低,无法连接数据库以保存一个复杂的viewmodel对象。以上只是一个简化的视图,并不那么复杂。 – twilliams

回答

2

如果您的视图模型是非常相似的形状,那么你应该能够使用联盟在一个查询得到一切,然后将行转换成相应的视图模型实例之后。类似以下内容 -

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 
     }) 
};