unbalanced
unbalanced

Reputation: 1202

Should I use an IQueryable list instead of entity in queries?

I coded an entity helper class and normally I use someting like that

  private CVSystemEntities db;

public EntityHelper()
    {

        db = new CVSystemEntities();
   }

   public IQueryable<Members> GetMembersForRole(Role role)
    {
        if (!RoleExists(role))
            throw new ArgumentException(MissingRole);

        return db.Members.Where(m => m.RoleID == role.Id).OrderBy(m=>m.Name).AsQueryable();
    }

its Okay but If I use something like that

  private CVSystemEntities db;
  private IQueryable<Members> membersDb;


public EntityHelper()
    {

        db = new CVSystemEntities();
        membersDb = db.Members.Select(s => s);
   }

   public IQueryable<Members> GetMembersForRole(Role role)
    {
        if (!RoleExists(role))
            throw new ArgumentException(MissingRole);

        return membersDb.Where(m => m.RoleID == role.Id).OrderBy(m=>m.Name).AsQueryable();
    }

I've used membersClass instead of db.members. I created an instead from db.members.

So, What do you think about this way? Should I use somekind of this? If you ask why you want to use it, I think that I don't query my db so much,maybe is better?

Upvotes: 0

Views: 139

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499790

Should I use somekind of this? If you ask why you want to use it, I think that I don't query my db so much, maybe is better?

No, you're doing exactly the same amount of work on the database. This:

membersDb = db.Members.Select(s => s);

... doesn't execute a query on the database and then retain the results, as I believe you expect it will. Instead, it effectively builds a query - but retains the query for later.

If you changed it to:

IEnumerable<Members> membersDb;
...
membersDb = db.Members.ToList();

then that would just hit up the database once - but of course then you'd get stale data if the database changed. Maybe that's okay - it's unclear what the lifetime of your EntityHelper is - but it seems unlikely to me. Note that the call to ToList would also fetch all the members from the database - whereas otherwise your queries will have appropriate Where clauses, restricting what's fetched. You probably don't want to fetch the whole table into memory, unless it's really small.

Upvotes: 3

Related Questions