Linq “Could not translate expression… into SQL and could not treat it as a local expression.”

后端 未结 3 1394
走了就别回头了
走了就别回头了 2020-11-30 12:47

I started out with this question, which I sort of answered there, and now I\'m asking the more fundamental question here. I\'ve simplified the query down to this:



        
3条回答
  •  余生分开走
    2020-11-30 13:21

    You could use AsEnumerable on the entity, but that would force it to bring back all the columns (even if not used); perhaps instead something like:

    var q1 = from ent in LinqUtils.GetTable()
             from tel in ent.Telephones.DefaultIfEmpty()
             select new {
               Name = ent.FormattedName,
               Number = (tel == null ? null : ent.Number),
               Extension = (tel == null ? null : ent.Extension)
             };
    
    var q2 = from row in q1.AsEnumerable()
             select new {
                 row.Name,
                 FormattedNumber = FormatNumber(row.Number, row.Extension)
             };
    

    where FormatNumber is some method that takes the two and merges them, presumably re-used from your other (property) code.

    With LINQ-to-SQL, another option is to expose a UDF on the data-context that does the formatting inside the database; a slightly different example:

    var qry = from cust in ctx.Customers // and tel
              select new {
                  cust.Name,
                  FormattedNumber = ctx.FormatNumber(tel.Number, tel.Extension)
              };
    

    (which will do the work at the database; whether or not that is a good idea ;-p)

提交回复
热议问题