0

我在 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() : ""
                  };

谢谢。

4

1 回答 1

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() : ""
     });
于 2012-09-14T11:55:20.173 回答