Reputation: 378
I get this error in LINQ to Entities: LINQ to Entities does not recognize the method 'System.String ToString()' method.
How should I solve this common problem?
Note that FleetViewModel.DWTStart is a string and fleet.DWTStart is a nullable decimal.
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() : ""
};
Thanks.
Upvotes: 0
Views: 401
Reputation: 1503090
Basically you need to do the final part in-process, which you can force with 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() : ""
});
If there's nothing else in the entity apart from these four properties, you can skip the anonymous type to start with - it's really only there to avoid fetching data you don't need:
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() : ""
});
Upvotes: 2