如何动态更改lambda表达式中的属性

时间:2014-01-01 11:20:23

标签: entity-framework

我在下面写了一个函数。在第二行代码中,我写了“Where(t => t.PickTicket == EmployeeId)”。我想动态更改(t.PickTicket)属性。我怎么能实现这个???如何让下面的代码更好更短?

提前致谢。

public List<TicketJoin> GetTicketJoin(string EmployeeId)
        {
            var query = _context.tickets.Where(t => t.PickTicket == EmployeeId).Join
                     (
                     _context.employees, t => t.CreatedBy, e => e.EmployeeId, (t, e) => new
                     {
                         t.Id,
                         e.Employee_Name,
                         e.Department,
                         e.Location,
                         t.Subject,
                         t.MainCatId,
                         t.SubCatId,
                         t.PickTicket,
                         t.Status,
                         t.CreateDate
                     }).Join
                     (
                     _context.MainCategory, t => t.MainCatId, m => m.MainCatId, (t, m) => new
                     {
                         t.Id,
                         t.Employee_Name,
                         t.Department,
                         t.Location,
                         t.Subject,
                         t.MainCatId,
                         m.MainCatName,
                         t.SubCatId,
                         t.PickTicket,
                         t.Status,
                         t.CreateDate
                     }).Join
             (
             _context.SubCategory, t => t.SubCatId, s => s.SubCatId, (t, s) => new
             {
                 t.Id,
                 t.Employee_Name,
                 t.Department,
                 t.Location,
                 t.Subject,
                 t.MainCatId,
                 t.MainCatName,
                 t.SubCatId,
                 s.SubCatName,
                 t.PickTicket,
                 t.Status,
                 t.CreateDate
             }).ToList();

            var TicketJoin = query.ToList().Select(r => new TicketJoin 
            {
                EmployeeName = r.Employee_Name, 
                Subject = r.Subject, 
                Location = r.Location, 
                MainCatName = r.MainCatName, 
                SubCatName = r.SubCatName, 
                CreateDate = r.CreateDate
            }).ToList();

            return TicketJoin;
        }
    }

1 个答案:

答案 0 :(得分:1)

如何缩短它?

通过使用数据库视图隐藏所有这些连接。在这种情况下,您将只有单一条件的简单查询。

如何让它变得动态?

你真的需要动态吗?你可以这样做:

public List<TicketJoin> GetTicketJoin(Expression<Func<Ticket, bool>> condition)
{
    var query = _context.Tickets.Where(condition)...  
}

并将其命名为

var result = this.GetTicketJoin(t => t.PickTicket == employeeId);

它不是完全动态的,但它允许调用指定条件的代码。

完全动态的解决方案,您可以将属性名称作为字符串传递,这需要使用表达式树来构建查询。为此还有一个Dynamic-Linq库。