【发布时间】:2016-04-22 18:54:50
【问题描述】:
我有一个由多对多关系组成的数据库,它使用联结表与其中一个表建立一对多关系。
我创建了以下查询:
Select Producto.Nombre, count(Producto.Nombre), Orden.Fecha
From Producto
INNER JOIN ProductoPedido
ON Producto.IdProducto = ProductoPedido.ProductoIdProducto
INNER JOIN Pedido
ON Pedido.IdPedido = ProductoPedido.PedidoIdPedido
INNER JOIN Orden
ON Pedido.OrdenNumeroOrden = Orden.NumeroOrden
GROUP BY Producto.Nombre, Orden.Fecha
如何使用 LINQ 在我的项目中创建完全相同的查询?
我尝试了以下方法,但它不起作用。
var data = (from producto in _context.Producto
join productopedido in _context.ProductoPedido on producto.IdProducto equals productopedido.ProductoIdProducto
join pedido in _context.Pedido on productopedido.PedidoIdPedido equals pedido.IdPedido
join orden in _context.Orden on pedido.OrdenNumeroOrden equals orden.NumeroOrden
group new { producto.Nombre, orden.Fecha } by new { producto, orden } into g
select new
{
Producto = g.Key.producto.Nombre,
Cantidad = g.Key.producto.Nombre.Count(),
Fecha = g.Key.orden.Fecha
});
每当我尝试访问 var 中的信息时,它都会返回 ArgumentException: Expression of type。
An unhandled exception occurred while processing the request.
ArgumentException: Expression of type 'System.Func`2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.Data.Entity.Storage.ValueBuffer,Microsoft.Data.Entity.Storage.ValueBuffer],Microsoft.Data.Entity.Storage.ValueBuffer],Microsoft.Data.Entity.Storage.ValueBuffer],<>f__AnonymousType3`2[System.String,System.Int32]]' cannot be used for parameter of type 'System.Func`2[<>f__AnonymousType2`2[System.String,System.DateTime],<>f__AnonymousType3`2[System.String,System.Int32]]' of method 'System.Collections.Generic.IEnumerable`1[System.Linq.IGrouping`2[<>f__AnonymousType3`2[System.String,System.Int32],<>f__AnonymousType2`2[System.String,System.DateTime]]] _GroupBy[<>f__AnonymousType2`2,<>f__AnonymousType3`2,<>f__AnonymousType2`2](System.Collections.Generic.IEnumerable`1[<>f__AnonymousType2`2[System.String,System.DateTime]], System.Func`2[<>f__AnonymousType2`2[System.String,System.DateTime],<>f__AnonymousType3`2[System.String,System.Int32]], System.Func`2[<>f__AnonymousType2`2[System.String,System.DateTime],<>f__AnonymousType2`2[System.String,System.DateTime]])'
System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
【问题讨论】:
-
始终显示完整的异常消息。此外,了解 LINQ 的类型是必不可少的(对实体而言?)。进一步:您应该使用导航属性而不是连接。