C# Generic Extension Method Help

Hi All,

I am trying to create a generic extension method for converting a List<T> to a List<SelectListItem> for dropdown lists in the view.

Now, I have the following Generic Repository System

    public interface IRepository<T>
    {
        void Insert(T entity);
        void Update(T entity);
        void Delete(T entity);
        IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
        IQueryable<T> GetAll();
        IOrderedEnumerable<T> GetPage(int pageIndex, int pageSize, string sortBy, string sortDirection);
        T GetById(int id);
    }

Open in new window


   public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        protected Table<T> DataTable;

        public Repository(DBDataContext dataContext)
        {
            DataTable = dataContext.GetTable<T>();
        }
        
        public Repository(DataContext dataContext)
        {
            DataTable = dataContext.GetTable<T>();
        }

        #region IRepository<T> Members

        public void Insert(T entity)
        {
            DataTable.InsertOnSubmit(entity);
        }

        public void Update(T entity)
        {
            DataTable.Attach(entity, true);
        }

        public void Delete(T entity)
        {
            DataTable.DeleteOnSubmit(entity);
        }

        public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
        {
            return DataTable.Where(predicate);
        }

        public IQueryable<T> GetAll()
        {
            return DataTable;
        }

        public IOrderedEnumerable<T> GetPage(int pageIndex = 0, int pageSize = 10, string sortBy = "ID", string sortDirection = "asc")
        {
            var param = Expression.Parameter(typeof(T));

            var sortExpression = Expression.Lambda<Func<T, object>>
                (Expression.Convert(Expression.Property(param, sortBy), typeof(object)), param).Compile();

            var results = DataTable.Skip((pageIndex - 1)*pageSize).Take(pageSize);

            switch (sortDirection.ToLower())
            {
                case "asc":
                    return results.OrderBy(sortExpression);
                default:
                    return results.OrderByDescending(sortExpression);
            }
        }

        public T GetById(int id)
        {
            return DataTable.Single(e => e.ID.Equals(id));
        }

        #endregion
    }

Open in new window


Where I entity is simply enforcing the ID

    public interface IEntity
    {
        int ID { get; }
    }

Open in new window


All the classes in my DBML are implementing IEntity.

and My Extensions Class is simply;

public static class RepositoryExtensions
    {
       public static IEnumerable<SelectListItem> ToSelectListItems<T>(
            this IEnumerable<T> items,
            Func<T, string> nameSelector,
            Func<T, string> valueSelector,
            Func<T, bool> selected)
       {
           return items.OrderBy(item => nameSelector(item))
                  .Select(item =>
                          new SelectListItem
                          {
                              Selected = selected(item),
                              Text = nameSelector(item),
                              Value = valueSelector(item)
                          });
       }
    }

Open in new window


Now for example when I try to get a dropdown list for all countries in my datbase as an example I have and call the following method

public static List<Country> GetCountries()
        {
            using (DBDataContext db = new DBDataContext())
            {
                return db.Countries.OrderBy(c => c.NiceName).ToList();
            }
        }

Open in new window


which I implment in the view as follows;

@Html.DropDownListFor(x => x.ID, Core.MiscRepository.GetCountries().ToSelectListItems("ID", "NiceName", true))

Open in new window


however, its not finding the extension method? Could anyone point me in the right direction please?

Many Thanks in Advance,

Matt.
flynnyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Gururaj BadamCommented:
Try including the extension method namespace in the Controller file where you have GetCountries defined.
0
käµfm³d 👽Commented:
You need to import the namespace, but not in the controller. Rather you need to import it in the view itself. You can do this via an @using statement:

e.g.

@model <your model class>

@using <the namespace that contains the RepositoryExtensions class>

<html>
...

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.