I am working on a small ASP.NET Core project to tag images using the Entity Framework Core in a Sqlite database, mainly for training. There are two tables (and POCOs), tags and images, where several tags are associated with each image. I am trying to get the number of all images that have tags associated with them.
In simple SQL, I would write SELECT COUNT(DISTINCT ImageId) FROM Tags to get a counter, and in LINQ I came up with _context.Tags.Select(t => t.Image).Distinct().Count() . But this LINQ query causes EF-Core to join the two tables, return all the rows, and then execute the Distinct and Count code.
I tried to do _context.Tags.FromSql("SELECT COUNT(DISTINCT ImageId) FROM Tags") , but since this query returns only the score caused by the failure, because EF cannot match the result with the tag. I also tried using _context.Database.FromSql<int> , but could not find any real documentation on it, and it does not look like IntelliSense to it.
Now I have done what is described in detail in the ADO.NET section of this blog post by Eric Anderson :
int count; using (var connection = _context.Database.GetDbConnection()) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT COUNT(DISTINCT ImageId) FROM Tags"; string result = command.ExecuteScalar().ToString(); int.TryParse(result, out count); } }
But is this the best way to use the account effectively?
Edit: Here is the request that EF places in Debug output:
SELECT "t"."TagId", "t"."Content", "t"."ImageId", "t.Image"."ImageId", "t.Image"."FileName", "t.Image"."Path", "t.Image"."Url" FROM "Tags" AS "t" LEFT JOIN "Images" AS "t.Image" ON "t"."ImageId" = "t.Image"."ImageId" ORDER BY "t"."ImageId"