如何在Linq to Entities查询中调用函数?

时间:2017-01-03 16:15:39

标签: c# linq

我有以下代码:

  public ActionResult Getinfobyid(int id)
    {
        //var req = db.td_adherent.Include(u => u.td_company).ToList();
        LoginSecretAttribute l = new LoginSecretAttribute();
        var req = from a in db.table 
                  join u in db.table2 on a.table1_id equals u.table2_id into us 
                  from u in us.DefaultIfEmpty()
                  select new
                  {
                     u = new
                    {
                       name = l.Decrypt(u.name),
                    }
                  }
        return Json(req, JsonRequestBehavior.AllowGet);
    }

我需要执行Decrypt函数

2 个答案:

答案 0 :(得分:0)

在使用自定义功能调用ToList之前,请务必致电ToArrayselect

    var req = (from a in db.table 
              join u in db.table2 on a.table1_id equals u.table2_id into us 
              from u in us.DefaultIfEmpty()).ToList();


     var req2 = from x in req
             select new
                {
                    u = new
                    {
                        name = l.Decrypt(x.name),
                    }
                }

原因是:LINQ to SQL是LazyLoaded,直到您实际访问它的结果。当您执行ToListToArrayFirstOrDefault,'AsEnumerable'等时,它实际上会调用db并获取数据。此时不再有LINQtoSQL并成为LINQtoObjects,它允许您使用您需要的任何方法。

请记住,执行后LINQtoObjects在内存中有效。所以所有数据都已从db下载。

答案 1 :(得分:0)

您可以使用AsEnumerable,以便在代码中调用您的方法,而不是Linq提供程序尝试将其转换为SQL。

public ActionResult Getinfobyid(int id)
{
    //var req = db.td_adherent.Include(u => u.td_company).ToList();
    LoginSecretAttribute l = new LoginSecretAttribute();
    var req = (from a in db.table 
               join u in db.table2 on a.table1_id equals u.table2_id into us 
               from u in us.DefaultIfEmpty()
               select u.name).AsEnumerable()
               .Select(n => new
               {
                   u = new
                   {
                       name = l.Decrypt(n),
                   }
               });
    return Json(req, JsonRequestBehavior.AllowGet);
}