在linq select中逗号分隔列表

时间:2014-08-26 09:52:00

标签: c# linq

我有表HR_Travel(TravelID,TravelCode ....)和HR_TravelDocuments(TravelDocID,TravelID,DocUrl)

        FromDate = FromDate.AddDays(1);
        ToDate = ToDate.AddDays(1);
        List<dynamic> Lst = new List<dynamic>();

        var queryTravelDetails = from t in db.HR_TravelDetails
                                 where ((t.StatusDate >= FromDate && t.StatusDate <= ToDate)
                                 && (t.EmpID == EmpID || EmpID == 0) && (t.TravelStatus == TravelStatus || TravelStatus == "All"))
                                 orderby t.StatusDate descending
                                 select new 
                                 {
                                     TravelID = t.TravelID,
                                     TravelSubID = db.HR_TravelDetails.Where(i => i.TravelID == 0).FirstOrDefault().TravelID == null ? 0 : db.HR_TravelDetails.Where(i => i.TravelID == 0).FirstOrDefault().TravelID,
                                     t.TravelCode,
                                     t.EmpID,
                                     EmpName = db.EE_Employee.Where(i => i.EmpID == t.EmpID).FirstOrDefault().EmpName,
                                     t.CellNo,
                                     t.BoardingForm,
                                     t.DestinationTO,
                                     t.JournyDate,
                                     t.Purpose,
                                     t.Organization,
                                     t.TravelStatus,

                                     DocUrl = DocUrl = string.Join(",",( db.HR_TravelDocuments.Where(i => i.TravelID == t.TravelID && i.TravelSubID == 0).Select(i => i.DocUrl).ToList()))
                                 };

  foreach (var element in queryTravelDetails)
        {
            Lst.Add(element);              
        }

给出以下错误:

LINQ to Entities does not recognize the method 'System.String Join[String](System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.

1 个答案:

答案 0 :(得分:0)

Join()方法不能在LINQ表达式中使用,因为它无法从CLR转换为T-SQL。另一个例子是你不能使用:

var itemCount = db.Table.Count(p => p.Something == SomeFunction(someVariable));

您应该将方法调用移到LINQ语句之外:

var anotherVariable = SomeFunction(someVariable);
var itemCount = db.Table.Count(p => p.Something == anotherVariable);

我希望我能以一种好的方式解释。

编辑:如前面的评论中所示,您也可以使用ToArray(),当本地加载数据时,您可以自由地使用语句中的函数。