How to always keep 1 record in BD after inserting with entityframework?

Asked

Viewed 111 times

1

I am developing in . NET MVC using Entity framework, how do I save a data by consulting if there is record or not in the table? 1.Query whether or not there is any data in the table 2.If you have any record, it adds replacing the previous element so there can be only 1 record in this table 3.if it does not enter normally

Is there any way to do this using entityframework? my method used in my Repository Class

      public void Inserir(Configuracoes configuracoes)
    {
        this.Context.Entry(configuracoes).State = EntityState.Modified;
    } 

1 answer

2

We need to contextualize the question so that this answer makes sense.

Yes. You should always search using FirstOrDefault(). If there are no records, the returned object will be null:

public ActionResult Index()
{
    var configuracoes = context.Configuracoes.FirstOrDefault();
    return View(configuracoes ?? new Configuracoes { ConfiguracoesId = Guid.NewGuid() });
}

What changes here is that I didn’t use a repository because the DbContext implemented by the Entity Framework is already a repository. Note that if the returned object is null, I create a new object with a generated id such as Guid:

return View(configuracoes ?? new Configuracoes { ConfiguracoesId = Guid.NewGuid() });

To know if the configuration already exists, before saving, repeat the selection on the object, but now without leaving the context observing. AsNoTracking() does that:

        var configuracoesOriginais = context.Configuracoes.AsNoTracking().FirstOrDefault();
        if (configuracoesOriginais != null) {
            context.Entry(configuracoes).State = EntityState.Modified;
        } else {
            context.Configuracoes.Add(configuracoes);
        }

If the record is null, need to add to context. Otherwise, just change the state and save.

  • You can do a search in the database returning only 1 object?

  • FirstOrDefault() fulfills this function. Brings only the first or brings null if there is no.

Browser other questions tagged

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