Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method on class - good or bad idea?

I already have Entity Framework in place along with a repository and some static classes/methods for manipulating the data. Here's a typical example:

public static IEnumerable<Supplier> Contains(IEnumerable<int> idList)
{
    return SupplierView.Select().Where(x => idList.Contains(x.ID));
}

These methods query my EF repository and sometimes I need to pass a number of variables to get the data I need back.

Given that my Supplier entity already exists, I'm contemplating making my queries extension methods using the class, something like this:

    public static IEnumerable<Supplier> GetSimilar(this Supplier s)
    {
        return SupplierView.Select().Where(/* the criteria matches */));
    }

It would only be used for querying data - but as I'm basing the extension method on the entire entity, I'm not sure whether this is a great design idea - but it's certainly more convenient that passing params/validating them etc.

I already have a partial class set up for my main entities, but I tend to add properties, low impact stuff.

Any thoughts?

like image 980
dotnetnoob Avatar asked Feb 26 '15 15:02

dotnetnoob


1 Answers

Is Supplier a class of your own?

If yes, then I'd recommend just extending that class - instead of tacking on extension methods.

If it's a class generated from the database by EF, it's a public partial class so you can easily write additional methods for Supplier in a second file, also using the public partial class - those are then merged into one single .NET class at compile time.

I like extension methods and they make a lot of sense - if you need to add methods to classes that you don't control - e.g. .NET framework classes, or third-party classes.

like image 95
marc_s Avatar answered Oct 09 '22 04:10

marc_s