Anthony
Anthony

Reputation: 135

c# need to have one extension method for various classes

What i am trying to do is i need to have one extension method for all my models.

Let's assume i have 3 class/models.

i am trying to do something like this in my extension method (was not able to succeed).

public static IQueryable<T> IncludeAllInfo<T>(this IQueryable<T> model)
    {
        if(model.getType().ToString() == "Model1")
        {
           var newModel = model.asQueryable<Model1>();

           return newModel.Include(a => a.Model2).Include(a => a.Model3);
        }
        elseif(model.getType().ToString() == "Model2")
        {
           var newModel = model.asQueryable<Model2>();

           return newModel.Include(a => a.Model3);
        }
    }

is this possible or must i create overload method for each type?

Upvotes: 1

Views: 111

Answers (2)

mohsen
mohsen

Reputation: 1806

Create one extension for every entity

    public static IQueryable<MyEntity> IncludeAllInfo(this Dbset<MyEntity> model)
    {

           return model.Include(a => a.Model3);

    }

Or

    public static IQueryable<MyEntity> IncludeAllInfo(this IQueryable<MyEntity> model)
    {

           return model.Include(a => a.Model3);

    }

Upvotes: 2

Igor
Igor

Reputation: 62213

You should create 1 method per type.

public static IQueryable<Model1> IncludeAllInfo(this IQueryable<Model1> model) { 
  return model.Include(a => a.Model2).Include(a => a.Model3);
}

public static IQueryable<Model2> IncludeAllInfo(this IQueryable<Model2> model) {
  return model.Include(a => a.Model3);
}

This is easier to test, maintain, read, and it is less code than what you have above.

Upvotes: 2

Related Questions