dotnet / dotnet/efcore

Map EntityType to IQueryable

Open
#30,146 1 comment 0 reactions 0 assignees View on GitHub
area-model-building area-query customer-reported needs-design
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

I have simple model with statistics. I would like to calculate statistics on the fly using provided IQueryable. I could use `ToSqlQuery` but I'm worried about column and table naming. Actually there is `ToQuery` method but it's deprecated and does not attach instance to navigation property (even with correct SQL).

Model
```C#
public class Car
{
public int CarId { get; set; }
public CarStatistics CarStatistics { get; set; }
}

public class CarStatistics
{
public int CarId { get; set; }
public int Mileage { get; set; }
}

public class Ride
{
public int RideId { get; set; }
public int CarId { get; set; }
public int Distance { get; set; }
}
```

Model Definition:
```C#
modelBuilder.Entity();
modelBuilder.Entity();
modelBuilder.Entity(c =>
{
c.HasKey(x => x.CarId);
c.ToQuery(() => Set().GroupBy(x => x.CarId).Select(g => new CarStatistics { CarId = g.Key, Mileage = g.Select(x => x.Distance).Sum() }));
});
```
and then use it as:
```C#
var query = context.Set().Include(x => x.CarStatistics).Take(1);
var car = query.ToList(); // <- there is no instance of CarStatistics in Car
```

Why there is no instance attached:
```
dbug: Microsoft.EntityFrameworkCore.Query[10107]
Generated query execution expression:
'queryContext => new SingleQueryingEnumerable(
(RelationalQueryContext)queryContext,
RelationalCommandCache.QueryExpression(
Client Projections:
0 -> Dictionary { [Property: Car.CarId (int) Required PK AfterSave:Throw ValueGenerated.OnAdd, 0] }
strange -->> 1 -> 1
strange -->> 2 -> 2
SELECT t.CarId, t0.CarId, t0.Mileage
FROM
(
SELECT TOP(@__p_0) c.CarId
FROM Car AS c
) AS t
LEFT JOIN
(
SELECT r.CarId, SUM(r.Distance) AS Mileage
FROM Ride AS r
GROUP BY r.CarId
) AS t0 ON t.CarId == t0.CarId),
null,
Func,
OemIq.RepairProcedures.Data.Contexts.RepairProceduresContext,
False,
False,
True
)'
```

EF Core version: 7.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.