简体   繁体   中英

Entity Framework DateTime to string?

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM