如何从linq到实体查询获取toTraceString()?

时间:2012-07-24 07:06:22

标签: c# .net entity-framework linq-to-entities

dynamic traceFile =  Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\EntityFrameworkTrace.log";                
var CurrentStock = (from s in DBViews.StockStatus
                    where s.ProductID != 10
                    orderby s.ProductName
                    select new
                    {
                        s.ProductID,
                        s.ProductName,
                        CurrentStock = s.TotalStocked - s.TotalSold,
                        s.CurrentSellingRate,
                        CashValue = (s.TotalStocked - s.TotalSold) * s.CurrentSellingRate,
                        s.LastStocked,
                        s.LastCostPrice,
                        s.LastQtyStocked
                    }).ToList();

File.AppendAllText(traceFile, CurrentStock.toTraceString());   
return CurrentStock.ToList();

如何从以下行中的CurrentStock获取toTraceString()?它没有得到解决

File.AppendAllText(traceFile,  CurrentStock.toTraceString()); 

1 个答案:

答案 0 :(得分:10)

你不能,因为你已经调用了ToList - 它不是Linq-to-Entities查询,只是一个List实例。

试试这个:

var CurrentStock = (from s in DBViews.StockStatus
                    where s.ProductID != 10
                    orderby s.ProductName
                    select new
                    {
                        s.ProductID,
                        s.ProductName,
                        CurrentStock = s.TotalStocked - s.TotalSold,
                        s.CurrentSellingRate,
                        CashValue = (s.TotalStocked - s.TotalSold) * s.CurrentSellingRate,
                        s.LastStocked,
                        s.LastCostPrice,
                        s.LastQtyStocked
                    }); // No ToList here!

File.AppendAllText(traceFile, ((ObjectQuery)CurrentStock).ToTraceString());   
return CurrentStock.ToList();

顺便说一下。为什么使用dynamic代替string?动态类型仅适用于有意义的特殊情况 - 事实并非如此。