What does this code do?
I have googled, but I don't quite understand what it does and how it works?
public void EntryCtrlFactura (RNFactura factura)
{
Entities db = new Entities();
ctrlFactura ctrlFactura = new ctrlFactura()
{
Id = factura.Id,
ProveedorId = factura.ProveedorId,
EstatusId = factura.EstatusId,
SNDistribuido = factura.SNDistribuido,
Referencia = factura.Referencia,
Importe = factura.Importe,
Impuesto = factura.Impuesto,
FechaRegistro = factura.FechaRegistro,
UsuarioReg = factura.UsuarioReg,
FechaEnvio = factura.FechaEnvio,
UsuarioEnv = factura.UsuarioEnv,
Observaciones = factura.Observaciones,
Concepto = factura.Concepto,
CveEmpresa = factura.CveEmpresa,
CveBodega = factura.CveBodega,
OcId = factura.OcId
};
using (var ctx = new Entities())
{
if (ctrlFactura.OcId == 0)
{
ctx.Entry(ctrlFactura).State = EntityState.Added;
}
else
{
ctx.Entry(ctrlFactura).State = EntityState.Modified;
}
ctx.SaveChanges();
}
}
}
EntityState is an enumeration with 5 possible values and even combinations between their values:
Added
modified
deleted
Unchanged
Detached
When you do operations using EntityFramework changes occur in the entity where those changes are being made, and those changes have a state, eg. if a record was modified the state of the entity is Modified , or if it was deleted it is Deleted .
When you do a SaveChange to the context, eg:
The EntityFramework goes through all the entities to see their status and if it detects that one has changed its status, then it makes this change effective and saves said data to the database , remember that in EntityFramework until you do SaveChanges the changes will not become effective in the database .
By marking the changes made on the entities with a state, the EntityFramework will know exactly what to do with that entity, that is, if the state of an entity is Modified , it knows that it must modify that data in the database and if it is Added , knows that it has to add it, so it will only do some action on the entities that have been changed in some way, that is, the one that its state is not Unchanged , this is efficiency, since if the state of the entity has not changed, Well , the EntityFramework simply doesn't touch it, it only works with the changed entities to record those changes in the database .
Once SaveChange is done , then the state of all entities will be Unchanged .
Looking at the Microsoft documentation, the state that you pass to it is that you use it or not depending on the method you use to add or update a record in the database.
Somehow or another that state is present in the transaction with the database.
https://docs.microsoft.com/es-es/ef/ef6/saving/change-tracking/entity-state