Reputation: 14998
I have a query given below in which I want to convert it's type.
Select
CONVERT(date, o.OrderDate)as OrderDate
From Orders
I am writing following statement:
var r= (
from o in db.Orders
select new { o.OrderNumber,o.Name,o.State,Convert.ToDateTime(o.OrderNumber) }
).ToList();
So it gives error:
Error 18 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
How do I deal with this conversion?
Upvotes: 2
Views: 119
Reputation: 2601
Try
var r= (from o in db.Orders
select new { o.OrderNumber,o.Name,o.State,
OrderDate = Convert.ToDateTime(o.OrderDate) }
).ToList();
Edit
Try this to materialize the query first.
var query = db.Orders.ToList().Select(o => new {
o.OrderNumber,
o.Name,
o.State,
OrderDate = Convert.ToDateTime(o.OrderNumber)
}).ToList();
Upvotes: 1
Reputation: 4594
When you execute your LINQ to Entities query it is converted to an equivalent database-side code using the underlying data provider.
It so happens that there is no mapping from Convert.ToDateTime()
to SQL Server equivalent.
Instead, you would do this in memory after you've retrieved the data as follows.
var r=
(from o in db.Orders
select new { o.OrderNumber, o.Name, o.State })
.AsEnumerable() // Execute the above query
.Select(order => new { order.OrderNumber, order.Name, order.State, OrderDate = Convert.ToDateTime(order.OrderNumber)})
.ToList();
(You could also split this into two queries for readability.)
There are also functions you can use in your L2E queries that are converted to their database equivalents.
See the SqlFunctions and the EntityFunctions classes for more information.
Upvotes: 0
Reputation: 77354
You need to name the members of your anonymous type. Sometimes the compiler will pick a name automatically (for example when you are assigning properties), but sometimes, it's not possible:
vvvv
new { o.OrderNumber, o.Name, o.State, OrderDateTime = Convert.ToDateTime(o.OrderNumber) }
Upvotes: 1
Reputation: 62296
That's mean that you need to assign names to the values of that anonymous memeber.
For example:
from o in db.Orders
select new { OrderNumber = o.OrderNumber, Name = o.Name,
State = o.State, Date = Convert.ToDateTime(o.OrderNumber) }
Upvotes: 1