使用连接转换LINQ到实体模型

时间:2014-03-17 18:41:45

标签: c# sql linq

我有两个实体,它们之间有外键,佣金和发票。我正在尝试使用ViewModel来包含联接中的数据,但我无法弄清楚如何投射它。如果我只是使用关系映射,它会在每次调用时执行选择,这是粗略的。

var commissions = from comm in db.Lead_Commission_Request
                  join inv in db.Lead_Referral_Invoice on comm.lead_commission_request_id equals inv.lead_commission_request_id
                  where inv.invoice_status_id == 0
                  select new InvoiceView
                  {
                      commission = comm,
                      invoices = inv
                  };

我已经使用子选择并将其转换为IEnumerable<>,但这仍然看起来很尴尬。

var commissions = from comm in db.Lead_Commission_Request
                  join inv in db.Lead_Referral_Invoice on comm.lead_commission_request_id equals inv.lead_commission_request_id
                  where inv.invoice_status_id == 0
                  select new InvoiceView
                  {
                      commission = comm,
                      invoices = (from invb in db.Lead_Referral_Invoice where comm.lead_commission_request_id == invb.lead_commission_request_id select invb)
                  };

public class InvoiceView
{
    public Lead_Commission_Request commission;
    public IEnumerable<Lead_Referral_Invoice> invoices;
}

1 个答案:

答案 0 :(得分:1)

使用GroupBy将您的行放在一起:

var commissions = from comm in db.Lead_Commission_Request
                  join inv in db.Lead_Referral_Invoice on comm.lead_commission_request_id equals inv.lead_commission_request_id
                  where inv.invoice_status_id == 0
                  group new { comm, inv } by comm.Id into g
                  select new InvoiceView
                  {
                      commission = g.FirstOrDefault().comm,
                      invoices = g.Select(x => x.inv)
                  };