我是数据库和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);
你为什么使用字符串来表示DateTime实例?你应该在Sql Server中使用.net(c#)和DateTime2(7)或DateTime中的'System.DateTime'(*你从未提及你的数据库服务器,如果它不是sql,那么使用任何类型的服务器来表示日期时间但它不会是字符串)*。此外,格式化日期(dd/mm/yyyy或mm/dd/yyyy或其他)是一种表示层解决方案,不应将其延续到持久层。 – Igor
你正在做你的日期一些奇怪的东西 – KSib
@Igor数据库的设计和人口在我的影响范围之外。不过,我可以影响我自己的ViewModel,所以是的,只是简单地解析它,然后显示为时间元素。 –