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?
– Hans Miller
FirstOrDefault()
fulfills this function. Brings only the first or brings null if there is no.– Leonel Sanches da Silva