I have the following method which simply iterates over orders grouped by client ID.
static void LinqWithInto()
{
using (var db = new EFContext())
{
var orders = db.Orders.Include(o => o.Client);
orders.Load();
var query = from order in orders
group order by order.ClientId into g
select new { ClientId = g.Key, Count = g.Count(), Orders = g };
foreach (var group in query)
{
WriteLine($"Client Id: {group.ClientId}, Number of orders: {group.Count}");
foreach (var order in group.Orders)
WriteLine($"\tOrder Id: {order.OrderId}, Client Id: {order.Client.ClientId}, Client Name: " +
$"{order.Client.Name} Payment: {order.Payment}");
}
}
}
The query fetches orders with associated clients:
[Table("Order")]
public class Order
{
public int OrderId { get; set; }
public int ClientId { get; set; }
public double Payment { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
}
[Table("Client")]
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<Order> Orders { get; set; }
}
The code works well in EF6, but in EF Core I get the following error (the variable query in foreach loop is highlighted):
System.ArgumentException: 'Expression of type 'System.Object' cannot be used for parameter of type 'Microsoft.EntityFrameworkCore.Metadata.IEntityType' of method 'Void StartTracking(System.Object, Microsoft.EntityFrameworkCore.Metadata.IEntityType)''
I wonder what's wrong here?
This seems to be a bug in EF Core 2.0 which got addressed in this issue (Contains workaround):
https://github.com/aspnet/EntityFrameworkCore/issues/9551
You can get the testfeed 2.0.3 here (Contains fix):
https://github.com/aspnet/Announcements/issues/274