Search code examples
c#entity-frameworkpartial

Entity Framework extension method (partial class)


Suppose I have following code

List<Common.Models.Log> logs = new MyEntities().Logs
            .OrderByDescending(o => o.Date)
            .Take(50)
            .ToList();

in need to create a partial class of "Logs" for call method like

List<Common.Models.Log> logs = new MyEntities().Logs.TakeFirst50OrderDateDesc();

Im trying to create the partial class for call the method from MyEntities().Logs

namespace Common.DataLayers
{
    public partial class Log : DbSet<Log>
    {
        public List<Log> TakeFirst50OrderDateDesc()
        {
            //blablabla
            return new List<Log>();
        }
    }
}

The problem is that I can't see TakeFirst50OrderDateDesc after new MyEntities().Logs. Is possible im wrong to define the constructor of the partial class? How I can solve it? Thanks


Solution

  • Try using an extension method like:

    public static IQueryable<Log> TakeFirst50OrderDateDesc(this IQueryable<Log> top50)
    {
        return top50.OrderByDescending(o => o.Date)
        .Take(50);
    
    }
    

    You can then access it exactly how you'd expect:

    var logs = context.Logs.TakeFirst50OrderDateDesc().ToList();