Entity Framework DateTime to string?

666 Views Asked by At

I'm trying to convert a datetime to a string, I'm using a foreach.

My code:

@foreach (var item in db.FrontTexts.Where(i => i.Placeholder == "Privacy"))
{
    <h2>@item.Heading</h2>
    @Html.Raw(item.Text)
    <p>This document was last updated: @item.LastUpdated.ToString("dd/MM/yyyy")</p>
}

It gives me a beautiful red line under "dd/MM/yyyy" saying:

Method "ToString" has 0 parameter(s) but is invokved with 1 argument.

When doing normal queries with WebMatrix.Data you can easily convert DateTime's to a string like above, so how would I achieve this in entity framework?

1

There are 1 best solutions below

0
On BEST ANSWER

For Nullable types there is ToString() method without parameter. so you have to first check it's not null and after that call ToString() method:

<p>This document was last updated: @if(item.LastUpdated.HasValue){<text>@item.LastUpdated.Value.ToString("dd/MM/yyyy")</text>}else{<text>N/A</text>}</p>