实体框架查询仅返回部分对象图
我在寻找这个特定问题的解决方案时有点头疼。 所以这里是: 假设我有 3 个表:
- 客户
- 订单
- 产品
我想检索客户及其订单的列表,并对某些客户和订单字段进行一些过滤,并返回一个仅显示每个实体的基本信息的图表。
例如,一个客户可能有 19 个字段,但我只想读取它的 ID、FirstName、LastName,并且从订单中,我只想读取 NetPrice 和相关产品 ID,以便在查询上发生迭代时,生成的 SQL 非常轻量级,只会选择那些特定字段。
这是可以实现的事情吗?如果是这样,怎么办?我很困惑如何做到这一点。
非常感谢。
编辑: 好吧,我已经成功做到了,而且现在速度很快!! 我是这样做的:
var customers = (from customer in Context.Cutomers
select new
{
customer.ID,
customer.FirstName,
customer.LastName,
Orders = customer.Orders.Select(order => new
{
order.ID,
order.NetPrice,
Products = order.Products.Select(product => new
{
product.ID
}
}
})
.AsEnumerable()
.Select(c => new Customer
{
c.ID,
//In my case, this is VERY important as it will
//try to convert from IEnumerable<T> to ICollection<T>
//which seems to need to be explicit.
Orders = c.Orders as ICollection<Order>
})
.ToList();
编辑#2: 我错了......它编译得很好,一切似乎都正常,但是,我的产品是空的...... 我又被难住了...
I'm having a bit of an headache finding a solution for this particular problem.
So here it is:
Lets say I have 3 tables:
- Customers
- Orders
- Products
I want to retrieve a list of customers and their orders with some filtering on some Customers' and orders' fields and return a graph that only shows basic informations of each entities.
For instance, a Customer could have 19 fields but I only want to read it's ID, FirstName, LastName and from the orders, I only want to read the NetPrice and the related product IDs in a way that when the iteration occurs on the query, the SQL that gets generated is very lightweight and will only select those specific fields.
Is it something that can be achieved? If so, how? I'm very puzzled on how to do this.
Thank you very much.
EDIT:
Ok, I've managed to do it and boy it's fast now!!
Here's how I did it:
var customers = (from customer in Context.Cutomers
select new
{
customer.ID,
customer.FirstName,
customer.LastName,
Orders = customer.Orders.Select(order => new
{
order.ID,
order.NetPrice,
Products = order.Products.Select(product => new
{
product.ID
}
}
})
.AsEnumerable()
.Select(c => new Customer
{
c.ID,
//In my case, this is VERY important as it will
//try to convert from IEnumerable<T> to ICollection<T>
//which seems to need to be explicit.
Orders = c.Orders as ICollection<Order>
})
.ToList();
EDIT #2:
I was wrong... It compiles fine, everything seems to be working but, my products are empty...
I'm stumped again...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用投影(匿名或准备好的类型)。我没有尝试过,但我认为这样的想法应该有效:
You can use projection (either to annonymous or prepared type). I didn't try it but I think somethink like this should work: