Search code examples
c#asp.net-mvcentity-frameworkdispose

Not Using Dispose or Using() in Entity Framework


I was writing a web app and learning entity framework along the way. I am curios if I have done something wrong though. I haven't been using dispose or using statements when querying.

Example of a Repository of mine:

public User GetUserById(int sessionId)
{
    var user = (from u in db.Users where u.Id == sessionId select u).SingleOrDefault();
    return user;
}

My User table I selected from would have foreign keys which would be associated with other tables. The cool thing, or so I thought, about entity is that I could return the entire User object (built by entity) which then would allow me to do something like this User.MyOtherTable.SomeColumn in my controller.

The problem is I relied on this and went about my merry way in my controller of grabbing the user information as well as utilizing information from the other table. I am now realizing that if I close that connection like the code below:

public User GetUserById(int sessionId)
{   using(db)
    {
    var user = (from u in db.Users where u.Id == sessionId select u).SingleOrDefault();
    return user;
    }
}

My controller no long has access to User.MyOtherTable.SomeColumn as this will be null. My true question is how important is it for me use dispose in my entity application?


Solution

  • I would strongly recommend that you use using statements, and also that you stop relying on lazy-loading.

    Instead of selecting User objects with lazy-load properties, work out the full data you need and project that to a Model class, e.g.

    public class UserWithOtherStuffModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string OtherStuff { get; set; }
    }
    

    Then in your method:

    public UserWithOtherStuffModel GetUserById(int sessionId)
    {
        using(db)
        {
            var user = (from u in db.Users 
                where u.Id == sessionId 
                select new UserWithOtherStuffModel{
                    Id = u.Id,
                    Name = u.Name,
                    OtherStuff = u.MyOtherTable.SomeColumn
                }).SingleOrDefault();
            return user;
        }
    }
    

    Not only does this mean you limit the number of database calls, but you have a data contract that isn't tied to your database model. If you move that column, you simply update the query to point to the new spot/name, the view can remain unchanged.