0

I've watched some class about Entity Framework with MySql and Sql Server. First the teacher uses the Entity from a database, where he creates the context DB and than he start the insert

using(sampleEntities ctx = new sampleEntities()){
client clt = new client();
clt.name = txtName.Text;
clt.phone = txtPhone.Text;
ctx.Add(clt);
ctx.SaveChanges();

But other teacher does something different with DAL, BLL and UI usgin session and httpContext, he says Entity needs this Session to avoid "persistence conflict" since the first example is using the same "connection/session" for lots of users, so that is what he does:

    public static sample01Entities Current
    {
        get
        {
               if (System.Web.HttpContext.Current.Session["SampleDbContext"] == null)
            {
                db = new sample01Entities();
                System.Web.HttpContext.Current.Session["SampleDbContext"] = db;
            }
            return db;

        }
    }

` and then in Dalcity

        public void Add(cidade c)
    {
        SampleDbContext.Current.cidade.Add(c);
        SampleDbContext.Current.SaveChanges();
        SampleDbContext.Current.ChangeTracker.Entries<cidade>();
    }

The question is: is it safe to use the first example without jeopardize a website? Or should I use the session all the time for all the CRUD methods?

Thanks

Jeú Casulo
  • 139
  • 2
  • 11

1 Answers1

0

Storing the context in the session is a terrible idea.

Read the following answer about it: Entity Framework Object Context in ASP.NET Session object?

The context should be either created by method or by request.

To answer to your question:

  • Yes it safe to use the first approach and for sure more recommended then storing the context in a session.
Community
  • 1
  • 1
Jonathan Magnan
  • 10,874
  • 2
  • 38
  • 60