1

I used to have a WORKING database for my ASP.NET site, up until the point that I've learned that using static Database Context objects throughout the app lifetime is a very bad practice.

So, initially, I used to have this:

    public class Database
    {
        MainDBContainer db;
        static Database()
        {
            db = new MainDBContainer();
        }
    }

    internal static SiteUser GetUser(string username)
    {
         return db.SiteUserSet.SingleOrDefault(u => u.Username == username);
    }

And, as you may guess, I've always used this static object to access/modify the database. Well, because of what I've read everywhere (that the static db context is bad), I decided to change the code to this:

    internal static SiteUser GetUser(string username)
    {
        //notice no static constructor for class.

        using (MainDBContainer db = new MainDBContainer())
        {
            return db.SiteUserSet.SingleOrDefault(u => u.Username == username);
        }
    }

The problem with this code (not particularly "this" very code, but the codes that modify something. by meaning this, I meant that I wrapped every db access with the using keyword just like this one), when db.SaveChanges() is called, it doesn't throw any exception, but nothing happens too. Within the same context, everything works, but that's it. NOTHING GETS WRITTEN TO THE ACTUAL SQL DATABASE. Before, I had everything set up and working and as soon as SaveChanges() was called, everything was immediately flushed to the database. My user authentication is even broken (straightforward: client sends username/passwordhash, and if its right server sends a random token, and client uses token with every request): User calls login method and successfully obtains a token, but whenever any other code interacts with the User object, from another context, the token is whatever the DB has before, and SaveChanges in the login method had no effect. It's the same for all methods, I just gave the Login one as a simple example. Am I missing something? Did I miss something obvious while porting code? Probably yes, but what's it?

Thanks, Can.

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
  • 1
    can you post a code segment where you save an entity? – Eranga Jul 05 '11 at 01:44
  • http://stackoverflow.com/questions/3594515/how-to-update-an-entity-in-entity-framework-4-net/3594608#3594608 – Ladislav Mrnka Jul 05 '11 at 08:17
  • `using (MainDBContainer db = new MainDBContainer()) { GlobalObject p = db.GlobalObjectSet.SingleOrDefault(i => i.ID == id); //p is guaranteed to be non-null due to a check before in the code. p.Title = title; p.Description = description; p.IsVisible = visible; TagObject(p, tags, usr); db.SaveChanges(); //this used to work perfectly, now it doesn't }` – Can Poyrazoğlu Jul 05 '11 at 09:54

1 Answers1

1

You've moved to a disconnected model. When a context is destroyed, EF no longer knows which objects are associated when you create a new instance on the next CRUD operation. Essentially, you manually have to tell EF about the objects you want to persist, and how to persist them.

For saving, you need to call AddObject on the context.

For updating, you call AttachTo and then ChangeObjectState or SetModifiedProperty on ObjectStateManager. (Note: this is only for completely disconnected objects: if you load an object and then make changes -- something you might do if you're doing row-level versioning -- EF already knows what to do because it has a built-in change-tracking mechanism, but only while the object is connected.)

For delete, you call AttachTo and then DeleteObject.

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
  • This is all *before* calling `SaveChanges`, which you still have to do. – Jon Seigel Jul 05 '11 at 02:56
  • Well, how can I simplify the process? Or how can I 'stay connected' somehow? I don't want to call attachto etc everywhere in the code, I just wasn't using it. In the previous model, I have never written AttachTo anywhere, not even once, I didn't get why this change broke my code. I'm no expert on EF, but logically, when you call SaveChanges(), it just should write to the database whatever you've changed or created. Even creating an object doesn't work anymore, I create a new entity, then save it in the same context, and it isn't saved. Nothing to do with another context. – Can Poyrazoğlu Jul 05 '11 at 09:59
  • @can: As I explained, when you destroy a context, EF no longer knows which objects have been persisted -- you have to tell it again. Generally this type of code goes into a data layer, where the methods are called centrally -- you only would have to call a `Save` method in one place. That kind of thing is beyond the scope of this discussion (doing a Google search should help). – Jon Seigel Jul 05 '11 at 11:46
  • I understand what you are telling. The context only knows about objects that it has loaded somehow (by selecting, editing, creating or deleting), it makes sense as a db context cannot load the data of the entire SQL server. But it STILL doesn't make sense that EF doesn't save an object that I've just created **in that context** and saving *in the same context**. I wasn't using AttachTo anywhere in my code and it used to work, and I don't get why it doesn't work now for **modifying/creating objects within the same context**. I mark this one, but I still have questions in mind. Thanks, though :) – Can Poyrazoğlu Jul 05 '11 at 13:25