Riccardo Pezzolati
Riccardo Pezzolati

Reputation: 359

How to generalize these linq queries

I Have this method:

 public IEnumerable<PackModel> PackLookup(short? society, string description)
        {
            return this.context.Pack.Where(x => x.Description.Contains(description) &&
                                                                        (!society.HasValue || x.Society == society))
                                                                       .OrderBy(x => x.Code)
                                                                       .Take(this.max);
        }

        public IEnumerable<FeaturesModel> FeaturesLookup(short? society, string description)
        {
            return this.context.Features.Where(x => x.Description.Contains(description) &&
                                                                    (!society.HasValue || x.Society == society))
                                                            .OrderBy(x => x.Code)
                                                            .Take(this.max);
        }

        public IEnumerable<ConstraintsModel> ConstraintsLookup(short? society, string description)
        {
            return this.context.Constraints.Where(x => x.Description.Contains(description) &&
                                                                    (!society.HasValue || x.Society == society))
                                                            .OrderBy(x => x.Code)
                                                            .Take(this.max);
        }

The three methods are very similar, only the DbSet changes, how could I make these calls in a generic way to avoid code duplication

Upvotes: 2

Views: 104

Answers (1)

DavidG
DavidG

Reputation: 118987

Assuming all your entity models share the same interface that has properties for Description, Code and Society, then you can abstract away using the Set<T> method of your DbContext and a generic type constraint, for example:

public IEnumerable<TModel> Lookup<TModel>(short? society, string description)
    where TModel : class, IYourInterface
{
    return this.context.Set<TModel>()
        .Where(x => x.Description.Contains(description) &&
                    (!society.HasValue || x.Society == society))
        .OrderBy(x => x.Code)
        .Take(this.max);
}

Now you call it like this:

var results = Lookup<PackModel>("society", "description");
var results = Lookup<FeaturesModel>("society", "description");
var results = Lookup<ConstraintsModel>("society", "description");

Upvotes: 3

Related Questions