dbContext static with Entity Framework: Compensates or not?

Asked

Viewed 136 times

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:

  1. What problems could occur with this type of use?
  2. 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)?

  • 1

    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.

  • 1

    It’s not worth it, the EF is based on the UoW. 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.

  • @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

  • @Renanvalentim Letting it burst is much better than ignoring it and creating a new one with the original message.

  • @Tobiasmesquita then the correct is always instantiate the Dbcontext in each method?

  • @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.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.