Groupby with if parameter using entity framework

c# entity-framework-6

Question

My service have a enum parameter and I need group by parameter value

I'm currently using if and tried with switch

My navigation property have property Name

Using if or Switch I duplicate my code Select(x =>

My model:

public class Bill
{
    public int Id {get;set;}

    public int CustomerId {get;set;}
    public Customer Customer {get;set;}

    public int BankAccountId {get;set;}
    public BankAccount BankAccount {get;set;}

    public int PlanId {get;set;}
    public Plan Plan {get;set;}

    public string Description {get;set;}
    public DateTime Date {get;set;}
    public decimal Amount {get;set;}
}

and my service return a DTO

public class BillService
{
     public BillDTO ReturnGroupBy(BillGroup group)
     {
            if (group== BillGroup.Customer)
            {
                return dbo.Bill.GroupBy(c => c.Customer).Select(c => new BillDTO { Nome = c.Nome })..
            }
            if(group== BillGroup.BankAccount)
            {
                return dbo.Bill.GroupBy(c => conta.BankAccount).Select(c => new BillDTO { Nome = c.Nome })..
            }

}
}
1
0
1/22/2019 2:53:35 PM

Popular Answer

You can declare the following class

public static class CustomQueryableExtensions
{
    public static IQueryable<IGrouping<INamed, T>> GroupByNamed<T>(this IQueryable<T> query, BillGroup group)
    {
        //enum name must be the same as property name
        string property = group.ToString();

        ParameterExpression parameter = Expression.Parameter(typeof(T));
        Expression prop = Expression.Property(parameter, property);

        var lambda = Expression.Lambda<Func<T, INamed>>(prop, parameter);

        return query.GroupBy(lambda);
    }
}

With interface

public interface INamed
{
    string Name { get; set; }
}

And use it like this

var bills = context
    .Users
    .GroupByNamed(BillGroup.Customer)
    .Select(u => new BillDTO { Name = u.Key.Name });

Notice that in my example User class has to contain Customer property and this property has to implement the INamed interface.

So in your case your Customer and BankAccount classes have to implement the same interface containing Nome property to be able to use this extension like this

dbo
    .Bill
    .GroupByNamed(BillGroup.Customer)
    .Select(c => new BillDTO { Nome = c.Key.Nome })..
0
1/22/2019 4:54:33 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow