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

1

I'm developing in .NET MVC using Entity framework, how do I save a data query whether there is a 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 may be 1 record in that table 3. if not it inserts normally

can you do this using entityframework? my method used in my Repository Class

      public void Inserir(Configuracoes configuracoes)
    {
        this.Context.Entry(configuracoes).State = EntityState.Modified;
    } 
    
asked by anonymous 12.03.2015 / 21:06

1 answer

2

The question needs to be contextualized for this answer to make sense .

Yes, it does. 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 did not use a repository because #. Note that if the returned object is null, I create a new object with an Id generated as DbContext :

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 looking. Guid does this:

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

If the record is AsNoTracking() , you must add it to the context. Otherwise, just change the state and save.

    
12.03.2015 / 21:30