Using a partial class property inside LINQ statement

后端 未结 6 869
灰色年华
灰色年华 2020-12-05 10:39

I am trying to figure out the best way to do what I thought would be easy. I have a database model called Line that represents a line in an invoice.

It looks roughly

6条回答
  •  粉色の甜心
    2020-12-05 11:16

    There is another way, which is a bit more complex, but gives you the ability to encapsulate this logic.

    public partial class Line
    {
        public static Expression> TotalExpression
        {
            get
            {
                return l => l.Price * l.Quantity
            }
        }
    }
    

    Then rewrite the query to

    var invoices = ( from c in _repository.Customers
                         where c.Id == id
                         from i in c.Invoices
                         select new InvoiceIndex
                         {
                             Id = i.Id,
                             CustomerName = i.Customer.Name,
                             Attention = i.Attention,
                             Total = i.Lines.AsQueryable().Sum(Line.TotalExpression),
                             Posted = i.Created,
                             Salesman = i.Salesman.Name
                         }
                   )
    

    It worked for me, performs queries server-side and complies with the DRY rule.

提交回复
热议问题