C # get this class to use generics

I have a class DbContextthat other classes extend. For instance:

class Contact extends DbContext {}

Inside the class, DbContextI want to use any class that extends DbContext in Generics:

  public static IEnumerable<DBContext> GetAll( )
  {
      var sql = "SELECT * FROM " + TableName();
      return DB().Fetch<DBContext> (sql);
  }

Note. IEnumerable <DBContext> here.

The above code is ok, but I have to type text every time. Can I achieve something thisClasslike:

public static IEnumerable<thisClass> GetAll( )
{
   var sql = "SELECT * FROM " + TableName();
   return DB().Fetch<thisClass> (sql);
}

Note. IEnumerable <thisClass> here.

After DStanley's comment:

I tried to do:

    public static IEnumerable<T> GetAll<T>()
    {
        var sql = "SELECT * FROM " + TableName();

        return DB().Fetch<T> (sql);
    }

But I do not want to call it that:

Contact.GetAll<Contact>();

Not clean. is not it?

Note: TableName () is nothing to worry about here. It gets the SQL methods in my path based on what class it is called.

+4
source share
3 answers

, .

DbContext<T> ( DbContext , ). :

public class DbContext<T> : DbContext
{
    public static IEnumerable<T> GetAll()
    {
        var sql = "SELECT * FROM " + TableName();

        return DB().Fetch<T> (sql);
    }
}

DbContext :

public class Contact : DbContext<Contact>
{

}

Contact.GetAll();.

+4

IEnumerable<Contact>, .

IEnumerable<Contact> contacts = Contact.GetAll()

.

+1

T, , :

  public static IEnumerable<T> GetAll( ) where T : DBContext
  {
    var sql = "SELECT * FROM " + TableName();
    return DB().Fetch<DBContext> (sql);
  }

, DBContext.

MSDN.

: , - , .

0

All Articles