ObjectContext、实体和加载性能
我正在编写一个 RIA 服务,它也使用 SOAP 公开。 它的方法之一需要从一个非常大的表中读取数据。
一开始我在做这样的事情:
public IQueryable<MyItem> GetMyItems()
{
return this.ObjectContext.MyItems.Where(x => x.StartDate >= start && x.EndDate <= end);
}
但后来我停止了,因为我担心表现。
据我了解,MyItemsis 已完全加载,“Where”只是过滤在第一次访问属性 MyItems 时加载的元素。因为 MyItems 确实有很多行,所以我认为这不是正确的方法。
我试着用谷歌搜索一下这个问题,但没有出现有趣的结果。
因此,我想我可以在 GetMyItems 方法中创建一个新的上下文实例并有选择地加载 MyItems。比如:
public IQueryable<MyItems> GetMyItems(string Username, DateTime Start, DateTime End)
{
using (MyEntities ctx = new MyEntities ())
{
var objQuery = ctx.CreateQuery<MyItems>(
"SELECT * FROM MyItems WHERE Username = @Username AND Timestamp >= @Start AND Timestamp <= @End",
new ObjectParameter("@Username", Username),
new ObjectParameter("@Start", Start),
new ObjectParameter("@End", End));
return objQuery.AsQueryable();
}
}
但我完全不确定这是正确的方法。
您能否帮助我并指出执行此操作的正确方法?
提前致谢, 干杯, 吉安卢卡.
I am writing a RIA service, which is also exposed using SOAP.
One of its methods needs to read data from a very big table.
At the beginning I was doing something like:
public IQueryable<MyItem> GetMyItems()
{
return this.ObjectContext.MyItems.Where(x => x.StartDate >= start && x.EndDate <= end);
}
But then I stopped because I was worried about the performance.
As far as I understand MyItemsis fully loaded and "Where" just filters the elements that were loaded at the first access of the property MyItems. Because MyItemswill have really lots of rows, I don't think this is the right approach.
I tried to google a bit the question but no interesting results came up.
So, I was thinking I could create a new instance of the context inside the GetMyItems method and load MyItems selectively. Something like:
public IQueryable<MyItems> GetMyItems(string Username, DateTime Start, DateTime End)
{
using (MyEntities ctx = new MyEntities ())
{
var objQuery = ctx.CreateQuery<MyItems>(
"SELECT * FROM MyItems WHERE Username = @Username AND Timestamp >= @Start AND Timestamp <= @End",
new ObjectParameter("@Username", Username),
new ObjectParameter("@Start", Start),
new ObjectParameter("@End", End));
return objQuery.AsQueryable();
}
}
But I am not sure at all this is the correct way to do it.
Could you please assist me and point out the right approach to do this?
Thanks in advance,
Cheers,
Gianluca.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,那是完全错误的。在真正遇到“性能问题”之前不要修复它们。您已有的代码可能比您建议替换的代码性能更好。它肯定不会按照您描述的方式运行。但不要相信我的话。使用性能分析器。使用 SQL 探查器。并测试!
No. That's entirely wrong. Don't fix "performance problems" until you actually have them. The code you already have is likely to perform better than the code you propose replacing it with. It certainly won't behave in the way you describe. But don't take my word for it. Use the performance profiler. Use SQL Profiler. And test!