首页 > 解决方案 > 使用实体框架的带有if参数的Groupby

问题描述

我的服务有一个枚举参数,我需要按参数值分组

我目前正在使用if并尝试使用switch

我的导航属性有属性Name

使用ifSwitch我复制我的代码 Select(x =>

我的模型:

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;}
}

我的服务返回一个 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 })..
            }

}
}

标签: c#entity-framework-6

解决方案


找到共同点并声明该类型的变量,在这种情况下IQueryable<Bill>

IQueryable<Bill> groupedBills;

if (group == BillGroup.Customer)
{
    groupedBills = dbo.Bill.GroupBy(c => c.Customer);
}
else
{
    groupedBills = dbo.Bill.GroupBy(c => conta.BankAccount);
}

return groupedBills.Select(c => new BillDTO 
{ 
    Nome = c.Nome,
    // ...
});

推荐阅读