I have the table VersionedEntities that looks like this:
+----+--------------+---------+
| Id | Name | Version |
+----+--------------+---------+
| 1 | FirstEntity | 1 |
+----+--------------+---------+
| 2 | SecondEntity | 2 |
+----+--------------+---------+
| 1 | ThirdEntity | 3 |
+----+--------------+---------+
Version is the primary key.
VersionedEntity class:
[Table("VersionedEntities")]
public class VersionedEntity
{
public int Id { get; set; }
public string Name { get; set; }
[Key]
public long Version { get; set; }
}
I want to select the latest version of each Id, resulting in this:
+----+--------------+---------+
| Id | Name | Version |
+----+--------------+---------+
| 2 | SecondEntity | 2 |
+----+--------------+---------+
| 1 | ThirdEntity | 3 |
+----+--------------+---------+
I already have a working query when using Microsoft SQL Server as database:
List<VersionedEntity> versionedEntities;
using (var dbContext = _createDbContext())
{
versionedEntities = dbContext.VersionedEntity
.GroupBy(versionedEntity => versionedEntity.Id)
.Select(group => group.OrderByDescending(versionedEntity => versionedEntity.Version).FirstOrDefault()).ToList());
}
I want to use SQLite as database instead, but when using SQLite the above query results in an NotSupportedException with the message: APPLY joins are not supported.
What I have found out is that only LEFT OUTER JOIN is implemented in SQLite (source). I guess that LINQ GroupBy() is using one of the not implemented joins.
I would like to know if there is a workaround to this, or if I could rewrite my query to something that is SQLite compatible.