在过去的几天里,我一直在研究使用实体框架v6的性能问题,没有办法解决这个问题。
我有一个对象A(在下面的例子中称为Company ),它包含第二个对象B的列表(下面的例子中的材料)。现在我想拿出一片A,并处理所有B类型的对象,这些对象包含在A中。在这个测试中,我使用了10000块B。
当我接收到对象时,服务器的响应时间是5-10秒,使用一种类型的访问,使用第二种类型的访问,它只使用0.2到0.3秒。我就是搞不懂为什么。
快速反应(~ 0.2 ~ 0.3s):EXAMPLE1
using (var cont = new Context())
{
Company C = cont.Companies.SingleOrDefault(o => o.ID == 18);
var mat = cont.Materials.Where(o => o.Company.ID == 18);
foreach (Material m in mat) { } // do stuff, does not matter
}慢反应(~ 5-10s):EXAMPLE2
using (var cont = new Context())
{
Company C = cont.Companies.SingleOrDefault(o => o.ID == 18);
var mat = C.materials; // takes forever
foreach (Material m in mat) { } // do stuff, does not matter
}对于我来说,第二种可能是缓慢的反应: EXAMPLE3
using (var cont = new Context())
{
cont.Configuration.LazyLoadingEnabled = false;
Company C = cont.Companies.Include(o => o.materials).SingleOrDefault(o => o.ID == 18); // takes forever
var mat = C.materials; // fast
foreach (Material m in mat) { } // do stuff, does not matter
}我就是想不出这个问题。我用一瞥来看时间线。问题是:在前两个示例中,SQL执行时间仅为100 ms。在示例2中,最后一次执行SQL与结束请求之间的时间间隔为5-10秒。在示例3中,SQL语句完全不同(而且很复杂),实际上需要5-10秒。示例1和示例2的SQL语句完全相同!
有人知道这是怎么回事吗?
以下是我的两个类的定义:
public class Company
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual List<Material> Materials { get; set; }
public Company()
{
}
}
public class Material
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Producer { get; set; }
[Required]
public virtual Company Company { get; set; }
public Material()
{
}
}发布于 2015-11-13 11:00:55
经过更多的测试后,我找到了一个解决方案,使所有查询都一样快。材料类需要直接引用公司类的索引。我认为这种方式的访问速度要快得多,因为对象不必每次加载?!我仍然不明白为什么第一个例子在原始类中是快速的。或者为什么在示例1和例2中SQL查询看起来完全相同,但性能差异很大。
public class Material
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Producer { get; set; }
[Required]
public int CompanyId { get; set; } // THIS IS NEW!!!
public virtual Company Company { get; set; }
public Material()
{
}
}https://stackoverflow.com/questions/33688784
复制相似问题