我是数据库和EF的新手。我在ASP.NET核心MVC项目中使用EF。下面的实现代码来自Controller,旨在将来自两个表的数据组合成摘要。
数据库有表格:Batch,Doc。
Batch有很多列,包括:int BatchId,string BatchEnd。 BatchEnd是一致的格式化DateTime,例如23/09/2016 14:33:21
Doc有许多列,包括:string BatchId,string HardCopyDestination。许多文档可以引用相同的BatchId,但所有这样做的文档都具有相同的HardCopyDestination值。
我想填充以下ViewModel
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);
答案 0 :(得分:0)
我认为你每批都要打一次数据库。如果你有很多批次很贵。您可以从db中一次性获取所有文档。
data.table
顺便说一下,Igor对日期是正确的,此外,如果BatchId中的BatchId是int,那么它也应该是DocTable中的。在上面的代码中,我假设它们是相同的类型,但如果不是这样,则不应该如此难以改变。
Igor关于分析db也是正确的,这是查看问题所在的好方法。我只是根据你的代码猜测。