0

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?

dafie
  • 951
  • 7
  • 25
  • 1
    Refer to [this](https://stackoverflow.com/questions/18976495/linq-to-entities-only-supports-casting-edm-primitive-or-enumeration-types-with-i), possibly the duplicate of yours. Regarding the first vs last: first is just `select top 1 * from XX` but last requires the order `select top 1 * from XX order by Id`. – Wiktor Zychla May 10 '19 at 12:26

1 Answers1

1

I was able to resolve this by adding the class generic type constraint to the extension method.

where T : class, IIDentity

public static class IQueryableExtensions
{
    public static T TakeLast<T>(this IQueryable<T> input) where T : class, IIDentity
    {
        return input
            .OrderByDescending(x => x.Id)
            .FirstOrDefault();
    }
}
Sebastian Siemens
  • 2,302
  • 1
  • 17
  • 24