Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it right to use extension methods in my case?

I use MVC4 and entity framework 5 in my project and I've lots of tables. As a rule of our project, we don't delete any records from database, each record has a isActive field and if that field is false, then we consider it deleted. I wanted to write an extension method to get active records and after some googling I wrote this:

public static IQueryable<Company> GetAll(this IQueryable<Company> source)
{
   return source.Where(p => p.isActive);
}

Now I can use my extension method to get only active records like

Context db = new Context();
db.Company.GetAll();

But let's say I've 50+ tables in my database, is it a good approach to write the same extension method for each of my tables. Is there a better way to write a only one GetAll() extension method for all of our tables? Actually I'm not even sure if is it right way to use extension methods for this instance?

Could somebody please help me and show me the right way? I appreciate if you help with code examples.

like image 637
cck Avatar asked Oct 21 '22 21:10

cck


1 Answers

It depends on how you are using Entity Framework, if you are depending on the normal generator (and I think you do), your case gets harder and I never had a similar case study. But, if you use normal POCO classes generator, you can use a base class let's call it CEntity which is a base class for each of your other classes (tables).

Are we there yet? No, to continue with this, I prefer to use the Repository Pattern, and you can make that repository generic (CEntity), for example:

public class Repository<CEntity> where CEntity : class
{
    public IQueryable<CEntity> GetAll()
    {
       return source.Where(p => p.isActive);
    }

}

And this is how to use it:

Repository<Company> com = new Repository<Company>();
Repository<Employee> emp = new Repository<Employee>();

var coms = com.GetAll();    // will get all ACTIVE companies
var emps = emp.GetAll();    // will get all ACTIVE employees

This is off the top of my head, if you had any other problems, put them as comments, glad to help.

like image 166
Ken D Avatar answered Oct 27 '22 16:10

Ken D