Search code examples
c#linqlinq-to-sqldevforce

Pass in an Expression to linq's Select


This is linq-to-sql

I have a lot of different classes all doing the same query, but projecting the results slightly differently. Ideally I'd like to be able to have the query in one place, and have the projection passed into the Select method. It works fine for concrete types:

public void GetResults() {
    var junk = db.SiteProducts.Select(Project());
}

public Expression<Func<DbEntities.SiteProduct, string>> Project() {
    return p => p.ProductAlert;
}

But when I try to return an anonymous type, it fails

public void GetResults() {
    var junk = db.SiteProducts.Select(Project());
}

public Expression<Func<DbEntities.SiteProduct, TResult>> Project<TResult>() {
    return p => new { p.ProductAlert };
}

I fully understand why generic type inference is failing in the second case. But is there a trick—short of crafting my own Expressions from the ground up—I'm missing that could get this to work?


Solution

  • If I understand your question correctly you can use this code:

    first declare a method for selecting your data like this:

    public List<TResult> FindAll<TResult>(Func<Regions, TResult> selector) where TResult : class
        {
            using (RepositoryDataContext = new DataClasses1DataContext())
            {
                    return RepositoryDataContext.Regions.Select<Regions, TResult>(selector).ToList<TResult>();
    
            }
        }
    

    then you can build your select statement like this:

    Func<Regions, SelectAllRegion> select = r => new SelectAllRegion
            {
                RegionID = r.RegionID,
                RegionDescription = r.RegionDescription
            };
    

    my SelectAllRegion :

     public class SelectAllRegion
    {
        public SelectAllRegion()
        {
        }
        public int RegionID { get; set; }
        public string RegionDescription { get; set; }
    }
    

    and region is Region table in northwing.I hope this help you