2016-09-19 35 views
0

我是数据库和EF的新手。我在ASP.NET Core MVC项目中使用EF。下面的实现代码来自Controller,旨在将来自两个表的数据合并为摘要。DB第一个实体框架查询非常慢

该数据库有表:批处理,文件。

批有很多列,包括:int BatchId,string BatchEnd。 BatchEnd是格式一致的DateTime,例如, 23/09/2016 14:33:21

Doc有很多列,包括:字符串BatchId,字符串HardCopyDestination。许多文档可以引用相同的BatchId,但是所有文档都具有相同的HardCopyDestination值。

我想填充以下视图模型

public class Batch 
{ 
    public int BatchId { get; set; } 
    public string Time { get; set; } // from BatchEnd 
    public string HardCopyDestination { get; set; } 
} 

但我当前的查询,下面,运行狗缓慢。我是否正确实施了这个?

var BatchViewModels = new List<Batch>(); 

// this is fine 
var batches = _context.BatchTable.Where(
        b => b.BatchEnd.Contains( 
         DateTime.Now.Date.ToString("dd/MM/yyyy"))); 


// this bit disappears down a hole 
foreach (var batch in batches) 
{ 
    var doc = _context.DocTable.FirstOrDefault(
        d => d.BatchId == batch.BatchId.ToString()); 

    if (doc != null) 
    { 
     var newBatchVM = new Batch 
     { 
      BatchId = batch.BatchId, 
      Time = batch.BatchEnd.Substring(whatever to get time), 
      HardCopyDestination = doc.HardCopyDestination 
     }; 

     BatchViewModels.Add(newBatchVM); 
     continue; 
    } 
} 

return View(BatchViewModels); 
+2

你为什么使用字符串来表示DateTime实例?你应该在Sql Server中使用.net(c#)和DateTime2(7)或DateTime中的'System.DateTime'(*你从未提及你的数据库服务器,如果它不是sql,那么使用任何类型的服务器来表示日期时间但它不会是字符串)*。此外,格式化日期(dd/mm/yyyy或mm/dd/yyyy或其他)是一种表示层解决方案,不应将其延续到持久层。 – Igor

+0

你正在做你的日期一些奇怪的东西 – KSib

+0

@Igor数据库的设计和人口在我的影响范围之外。不过,我可以影响我自己的ViewModel,所以是的,只是简单地解析它,然后显示为时间元素。 –

回答

0

我觉得你每次打一次数据库。如果你有很多批次很贵。您可以一次从数据库中获取所有文档。

var batchDict = batches.ToDictionary(b => b.BatchId); 
var documents = _context.DocTable.Where(doc => batchDict.Keys.Contains(doc.BatchId)); 
BatchViewModels.AddRange(documents.Select(d => new Batch 
{ 
    BatchId = d.BatchId, 
    Time = batchDict[d.BatchId].BatchEnd.TimeOfDay, // you only want the time? 
    HardCopyDestination = d.HardCopyDestination 
}); 

顺便说,伊戈尔是正确的日期时,此外,如果BatchId是int类型BatchTable,那么它应该是在DocTable为好。在上面的代码中,我假设它们是相同的类型,但如果它们不是那么难以改变。

伊戈尔也是正确的关于分析数据库是一个很好的方式来看看问题是什么。我只是根据你的代码猜测。