如何将带有语句主体的lambda表达式转换为表达式树

时间:2018-12-28 10:51:55

标签: asp.net-mvc asp.net-core

我的代码有问题,我不知道问题,因为C#是新手,但是我试图将项目从Asp.Net MVC转换为Core。有人可以帮我这个代码。

        using (var context = new UniversityDbContext())
        {
            var  payments =
                (from p in context.Payments
                    .FromSql(
                        "select * from dbo.Payments p inner join dbo.Bills b on p.BillId = b.Id where p.OrderStatus = \'Approved\' order by p.Service")
                 join b in context.Bills on p.BillId equals b.Id
                 where b.User == userId
                 select new { p, b })

            //error is from this   .Select(x =>
                 {
                     x.p.Bill = x.b;
                     return x.p;
                 }).ToList();   // To this

            var t = payments.Count();


            return payments;
        }

2 个答案:

答案 0 :(得分:0)

如果定义了Context.Payments.Bills 那么您可以使用下面的代码

  context.Payments.FromSql(
      "select * from dbo.Payments p where p.OrderStatus = 'Approved' order by p.Service").Include(x => x.Bills);

还需要在付款p.Bills内退还账单

参考:https://docs.microsoft.com/en-us/ef/core/querying/raw-sql#including-related-data

答案 1 :(得分:0)

对于lambda expression with statement body to an expression tree这个问题,您无法将x.p.Bill = x.b;传递给linq查询语句,请尝试如下操作:

using (var context = new UniversityDbContext())
{
    var  payments =
        (from p in context.Payments
            .FromSql(
                "select * from dbo.Payments p inner join dbo.Bills b on p.BillId = b.Id where p.OrderStatus = \'Approved\' order by p.Service")
            join b in context.Bills on p.BillId equals b.Id
            where b.User == userId
            select new { p, b })
            .ToList()
            .Select(x =>
            {
                x.p.Bill = x.b;
                return x.p;
            }).ToList();   // To this

    var t = payments.Count();
    return payments;
}