Linq类型转换问题
为什么这个东西在第二行中给出消息(即列表转换)?
IEnumerable<Order> MyQuery = from order in dataContext.GetTable<Order>()
where order.ID == 1
select new Order() {ID = order.ID, OrderDate=order.OrderDate };
List<Order> list = new List<Order>(MyQuery);
消息:
Explicit construction of entity type 'Order' in query is not allowed.
如果它已转换为 IEnumerable。将其转换为列表有什么问题?
同样,如果我写下以下内容,它就会起作用:
IEnumerable<Order> MyQuery = from order in dataContext.GetTable<Order>()
where order.ID == 1
select order;
List<Order> list = new List<Order>(MyQuery);
为什么?有什么窍门呢?
Why is this thing giving the message in the second line (i.e. list convertion)?
IEnumerable<Order> MyQuery = from order in dataContext.GetTable<Order>()
where order.ID == 1
select new Order() {ID = order.ID, OrderDate=order.OrderDate };
List<Order> list = new List<Order>(MyQuery);
The message:
Explicit construction of entity type 'Order' in query is not allowed.
If it is already converted into an IEnumerable. The what is its problem to convert it into a List?
Again, if I write the following, it works:
IEnumerable<Order> MyQuery = from order in dataContext.GetTable<Order>()
where order.ID == 1
select order;
List<Order> list = new List<Order>(MyQuery);
Why? What is the trick?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题不在于列表构造,而在于这一行:
问题是您无法在查询中显式创建实体。当您尝试创建列表时会发生这种情况,因为由于查询的延迟执行,直到您尝试将其包装在
new List
行中时,IEnumerable 才会被实际枚举。您似乎正在尝试检索订单本身。答案可能是只选择订单,而不是尝试构造新订单:
此外,没有理由将其设为可枚举,然后将其转换为列表。你可以这样做:
The problem isn't in the list construction, it's in this line:
The issue is that you cannot explicitly create an entity within a Query. This is occurring when you try to create your list because the IEnumerable is not actually enumerated until you try to wrap this in the
new List<Order>
line due to deferred execution of your query.It looks like you're trying to retrieve the orders themselves. The answer is probably to just select the order, and not try to construct a NEW order:
Also, there is no reason to make the enumerable, then turn it into a list. You can just do:
此问题的第一个答案帖子说明了正在发生的事情。
考虑一下,您可以使用 .ToList() 方法转换为列表。
The first answer to this post illustrates what's going on.
Consider, you can use the .ToList() method to convert to a list.
好吧,只有在将查询转换为列表时,您才真正执行查询。在此之前它只是一个任意的
IQueryable
。两个选项(假设您试图避免获取所有其他列):
使用匿名类型:
使用
AsEnumerable
在从 LINQ 提供程序获取新订单后创建新订单。请注意,此时它们还不是正确的实体:Well, you're only really executing the query when you convert it to a list. Before that it's just an arbitrary
IQueryable
.Two options (assuming you're trying to avoid fetching all the other columns):
Use an anonymous type:
Use
AsEnumerable
to create new orders after they've come down from the LINQ provider. Note that they won't be proper entities at this point: