These are my databse models:
public interface IIDentity
{
int Id {get; set;}
}
public class BaseModel : IIDentity
{
[Key]
public int Id { get; set; }
}
[Table("user")]
public class User : BaseModel
{
public string name {get; set;}
}
What I want to do is to get last user from table. This is not working.
context.user.LastOrDefault();
For some reason linq to entities
does not provide LastOrDefault()
(but FirstOrDefault()
is working)
I can make it working by:
context.user.OrderByDescending(x => x.Id).FirstOrDefault();
Then, I want to make it more generic:
public static class IQueryableExtensions
{
public static T TakeLast<T>(this IQueryable<T> input) where T : IIDentity
{
return input
.OrderByDescending(x => x.Id)
.FirstOrDefault();
}
}
But I am getting error:
'Unable to cast the type 'User' to type 'IIDentity'. LINQ to Entities only supports casting EDM primitive or enumeration types.'
Is there anything I can do about it?