How to recover date from SQL Server correctly? [closed]

0

I created a simple CRUD using the ASP.NET MVC and I can save my records normally. If I looked in the database, my date ( DataCriation ) was stored like this:

  

2017-06-01 00: 01: 23,750

But when I try to edit the same record with an asynchronous method created by MVC Scaffolding, all fields in the table are retrieved, but the DataCriation appears to be null: p>

  

01/01/2000 00:00:00

Then (obviously) I get an error:

  

Converting a datetime2 data type to a data type   datetime resulted in a value out of reach.

This is the generated method:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ArtigoId,Titulo,Texto,DataPublicacao,UltimaModificacao,UsuarioModificacao,DataCriacao,UsuarioCriacao")] Artigo artigo)
{
    if (ModelState.IsValid)
    {
        db.Entry(artigo).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(artigo);
}

After the problem I did some research and changed the field in the database to datetime2(0-7) in EF Code First doing this in my model:

[DisplayName("Data de Criação")]
[Column(TypeName = "datetime2")]
public DateTime DataCriacao { get; set; }

This did not correct the problem, just made the field accept the 01/01/2000 00:00:00 date.

How do I retrieve the date correctly? Should I use datetime or datetime2?

    
asked by anonymous 06.06.2017 / 00:01

1 answer

1

The problem occurred because I removed my View field and has nothing to do with the date format in SQL Server.

I put the field back in View as readonly :

<div class="form-group">
    @Html.LabelFor(model => model.DataCriacao, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DataCriacao, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
        @Html.ValidationMessageFor(model => model.DataCriacao, "", new { @class = "text-danger" })
    </div>
</div>

The search of the field in the DB is done in the GET method:

// GET: Artigos/Edit/5
public async Task<ActionResult> Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Artigo artigo = await db.Artigoes.FindAsync(id);
    if (artigo == null)
    {
        return HttpNotFound();
    }
    return View(artigo);
}

The method I posted was POST after the submit of my button to save changes and no searches were made to the database.

    
06.06.2017 / 01:47