Reputation: 11
I used in EF Expression Like this,
query
.Select(item => new
{
DoubleValue =
new List<string>() { item.AdmissionTicketCode }
.Cast<double>()
.FirstOrDefault()
})
.ToList();
but, run at Unit Test it thorw an error "Specified Cast Is Not Valid".
how do I deal this problem
I tried to add System.Linq.Fakes、and wanted use ShimEnumerable to resolve it, but it does not exist in System.Linq.Fakes.
Upvotes: 1
Views: 68
Reputation: 117175
.Cast<double>()
is a NOP on a double and will throw on any other type. Also, keep in mind, that a cast is not a conversion. If item.AdmissionTicketCode
is a string then you need to parse it, not cast it.
So let's break down what you might need to do.
Your current code is equivalent to:
query
.Select(item => new
{
DoubleValue = (double)item.AdmissionTicketCode
})
.ToList();
Assuming that item.AdmissionTicketCode
is a string
then the compiler lets us know it's a bad cast right now.
So it should be like this:
query
.Select(item => new
{
DoubleValue = double.Parse(item.AdmissionTicketCode)
})
.ToList();
It's a bit pointless having a single property in an anonymous type, so you could go one step further:
query
.Select(item => double.Parse(item.AdmissionTicketCode))
.ToList();
If EF doesn't support double.Parse
then do this:
query
.Select(item => item.AdmissionTicketCode)
.ToList()
.Select(x => double.Parse(x))
.ToList();
Upvotes: 0