How to Recover SQL Server Data Correctly?

Asked

Viewed 149 times

0

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

2017-06-01 00: 01: 23.750

But when I try edit the same record with an asynchronous method created by MVC Scaffolding, all fields in the table are recovered, but the Dating appears to be void:

01/01/2000 00:00:00

So (obviously) I get an error:

Conversion of a data type2 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) on EF Code First doing this on my model:

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

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

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

1 answer

1


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

I put the field back on 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 field search in the BD 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 the POST after the Submit of my button to save the changes and no searches were made in the database.

  • Just a tip, avoid recording date and time together if you need, record separately, so you can avoid future problem related to data query.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.