I know that LINQ to SQL does not convert DateTime
to string
since there is no ToString()
in SQL.
But how can I convert the DateTime
into a formatted string?
This is the line in the following query that needs help:
StartDate = string.Format("{0:dd.MM.yy}", p.StartDate)
The whole query:
var offer = (from p in dc.CustomerOffer
join q in dc.OffersInBranch
on p.ID equals q.OfferID
where q.BranchID == singleLoc.LocationID
let value = (p.OriginalPrice - p.NewPrice) * 100 / p.OriginalPrice
orderby value descending
select new Offer()
{
Title = p.OfferTitle,
Description = p.Description,
BestOffer = value,
ID = p.ID,
LocationID = q.BranchID,
LocationName = q.CustomerBranch.BranchName,
OriginalPrice = SqlFunctions.StringConvert((decimal)p.OriginalPrice),
NewPrice = SqlFunctions.StringConvert((decimal)p.NewPrice),
StartDate = string.Format("{0:dd.MM.yy}", p.StartDate)
}).First();
I get the following error message:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
I ended up using the sql function
FORMAT
; here's a simplified version of this implementation:https://weblogs.asp.net/ricardoperes/registering-sql-server-built-in-functions-to-entity-framework-code-first
First you need to define the function in EF:
Then define it as C# methods:
Register it in your
DbContext
:And finally, you can call it like so:
Another option is using SqlFunctions.DateName , your code will be like this:
I found it useful if you don't want to add an extra select new block.
if it's a datetime you need to use the
.ToShortDateString()
. But you also need to declare it AsEnumerable().EDIT: Now that I understand the question, I'm giving it another shot :)
I know it's a bit long, but that's the problem with Linq To SQL.
When you use linq, the database call isn't executed until you use something such as ToList() or First() that results in actual objects. Once that SQL call is executed by the first .First() call, you're now working with .NET types, and can use DateTime stuff.
That is what we did, we added a new function to the class and we query the date as normal in the query:
Then you can just call the FormattedDate field passing the desired format.
Or can can define it as a field with just the getter:
In case you class is an Entity, you need to declare a new partial of that class and add the field.
Hope this help someone.