Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Find method as IQueryable

I have this in my repository and it works as expected:

public virtual EntityClass GetById(int id)
{
    return db.Set<EntityClass>().Find(id);
}

However, I have some tables with either too many columns (example: 10 columns where I need only 3 out of them) or some tables where I have long text in there and again, they dont need to be fetched.

I was thinking if there is a way to still search by the primary key but perhaps getting an IQueryable result? Or at least something that could allow me to do something like this:

var blah = myRepo.GetById(myId).Select(s => new {column 2, column 3, column 7})
like image 764
WPalombini Avatar asked May 26 '15 05:05

WPalombini


1 Answers

I would create another class that contains the subset of the properties that you want. That way it should always be clear what you are working with:

public class EntityClassLite
{
   public int Id {get; set;}
   public string Column2 {get; set;}
   public string Column3 {get; set;}
   public string Column7 {get; set;}
}

Then you could have a separate method in your repository:

public EntityClassLite GetLiteById(int id)
{
    return db.Set<EntityClass>()
             .All
             .Where(e => e.Id = id)
             .Select( new EntityClassLite
                    {
                       Column2 = e.Column2
                       Column3 = e.Column3
                       Column7 = e.Column7
                    }
             .FirstOrDefault()
}

You could also think about using inheritance:

public class EntityClass: EntityClassLite
{
   public string Column1 {get; set;}
   public string Column4 {get; set;}
   public string Column5 {get; set;}
   public string Column6 {get; set;}
   public string Column8 {get; set;}
   public string Column9 {get; set;}
   public string Column10 {get; set;}
}

Then you would have two repositories. One for EntityClass and one for EntityClassLite, each with their own Find method and each returning the data you require.

As an aside, I find it very hard to imagine an entity that has such large columns that fetching a single instance of it would cause significant performance problems.

like image 64
Colin Avatar answered Sep 28 '22 21:09

Colin