0
Guys, I use Entity Framework and Code First to manage my data access, and I’m thinking of working with a single instance, static and global of my Databasecontext. But I have two questions:
- What problems could occur with this type of use?
- Is there an example Project Pattern for this?
Here’s an example of how to access data in my database:
CURRENTLY - Each method calls an instance of the Basedata
using (var db = new BaseDados())
{
var fatura = db.Contas_Receber.Where(x => x.Chave == chaveFatura).FirstOrDefault();
}
SUBSEQUENTLY - There will be only one instance of Basedata, and all Daos in my system will use this instance.
public static class DAO<T> where T : class
{
private static SETCOM_BaseDados db;
public static void Create(T entidade)
{
db.GetInstance();
try
{
db.Set<T>().Add(entidade);
((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.ChangeObjectState(entidade, System.Data.Entity.EntityState.Added);
}
catch (Exception ex)
{
throw new Exception("Erro ao inserir dados : " + ex.Message);
}
}
}
public static class BaseDadosExtension
{
public static SETCOM_BaseDados GetInstance(this BaseDados db)
{
return (db == null ? new BaseDados() : db);
}
}
Call to create a new Count on receiving:
Contas_Receber cr = new Contas_Receber();
cr.Valor = 0;
cr.Cliente = new Cliente();
DAO<Contas_Receber>.Create(cr);
(Possible) Problem 1: Will leave the context always "open" (without Disposis)?
– Jéf Bueno
Problem #2: The exception treatment is awful, throwing the stacktrace away and paying attention to the message is one of the worst things you can do with an exception.
– Jéf Bueno
It’s not worth it, the
EF
is based on theUoW
. As you are doing, this unique context will start to track all and whatever entity is consulted, this way, each operation will be slower and consuming more memory, eventually your application will die.– Tobias Mesquita
@Could LINQ give me an example of how to treat it correctly? I have an extension created for Exception here called "Getallmessages" and I use it to get the full Stacktrace, this Try catch is just for this example
– Renan Valentim
@Renanvalentim Letting it burst is much better than ignoring it and creating a new one with the original message.
– Jéf Bueno
@Tobiasmesquita then the correct is always instantiate the Dbcontext in each method?
– Renan Valentim
@Renanvalentim if you have nothing to do, such as closing a connection, disrupting an operation, releasing a resource, etc... then you don’t need to treat, let Exception flow and treat it only in your global exception treatment.
– Tobias Mesquita