LINQ to Entities ToString()出错

时间:2012-09-14 11:42:21

标签: linq linq-to-entities

我在LINQ to Entities中遇到此错误:LINQ to Entities无法识别方法'System.String ToString()'方法。
我该如何解决这个常见问题?

请注意,FleetViewModel.DWTStart是一个字符串,fleet.DWTStart是一个可以为空的十进制数。

            var qry = from fleet in _entitiesContext.Fleets
                  select new FleetViewModel
                  {
                      FleetID = fleet.FleetID,
                      FleetName = fleet.FleetName,
                      DWTStart = fleet.DWTStart.HasValue?fleet.DWTStart.Value.ToString():"",
                      DWTEnd = fleet.DWTEnd.HasValue ? fleet.DWTEnd.Value.ToString() : ""
                  };

感谢。

1 个答案:

答案 0 :(得分:2)

基本上你需要在进程中完成最后一部分,你可以用AsEnumerable强制执行:

var qry = _entitiesContext.Fleets
    .Select(fleet => new { fleet.FleetID,
                           fleet.FleetName,
                           fleet.DWTStart,
                           fleet.DWTEnd })
    .AsEnumerable() // Do the rest in-process
    .Select(fleet => new FleetViewModel {
        FleetID = fleet.FleetID,
        FleetName = fleet.FleetName,
        DWTStart = fleet.DWTStart.HasValue?fleet.DWTStart.Value.ToString():"",
        DWTEnd = fleet.DWTEnd.HasValue ? fleet.DWTEnd.Value.ToString() : ""
     });

如果除了这四个属性之外,实体中没有其他内容,您可以跳过匿名类型开始 - 它实际上只是为了避免获取您不需要的数据:

var qry = _entitiesContext.Fleets
    .AsEnumerable() // Do the rest in-process
    .Select(fleet => new FleetViewModel {
        FleetID = fleet.FleetID,
        FleetName = fleet.FleetName,
        DWTStart = fleet.DWTStart.HasValue?fleet.DWTStart.Value.ToString():"",
        DWTEnd = fleet.DWTEnd.HasValue ? fleet.DWTEnd.Value.ToString() : ""
     });