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.