简体   繁体   中英

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?

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 - eg .NET framework classes, or third-party classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM