dblwizard
dblwizard

Reputation: 627

Property Type as Generic parameter

I'm trying to figure out how I can make a Generics call take a variable for the Type. In the call below it take a type "DAL.Account" and works fine.

var tst = ctx.GetTable<DAL.Account>().Where(t => t.Sbank == "000134");

I want to change that so that I can pass a variable in place of the "DAL.Account". Something like this but I know that won't work as you can't pass property as a Type.

ctx.GetTable<Criteria.EntityType>().Where(LinqToSQLHelper.BuildWhereStatement(Criteria.StateBag), Criteria.StateBag.Values.ToArray())

Below is the shell pieces of code I think explains what I'm trying to do. Generics is not my strong suit so I'm looking for some help. Is there anyway that I can make this happen?

//Stores a "Type" that indicates what Object is a Criteria for.
public class AccountCriteria : IGeneratedCriteria
{
    ...

    public Type EntityType
    {
        get {return typeof(DAL.Account);}
    }
}

//I have added a function to the DataContext called "GetTable"
// And then used it as an example in a Console App to test its functionality.
public class ADRPDataContext : NHibernateDataContext
{
    ...

    public CodeSmith.Data.NHibernate.ITable<T> GetTable<T>() where T : EntityBase
    {
         var tb = new CodeSmith.Data.NHibernate.Table<T>(this);
         return tb;
    }
}

// console application that uses DataContext.GetTable
class Program
{
    static void Main(string[] args)
    {
        using (var ctx = new ADRPDataContext())
        {
            var tst = ctx.GetTable<DAL.Account>().Where(t => t.Sbank == "000134");
        }
    }
}

//ExistsCommand class that uses the EntityType property of the Critera to generate the data.
public class ExistsCommand
{
    private IGeneratedCriteria Criteria { get; set; }

    protected override void DataPortal_Execute()
    {
        using (var ctx = new DC.ADRPDataContext())
        {
            //This was my first attempt but doesn't work becuase you can't pass a property in for a Type.
            //But I can figure out how to write this so that it will work.
            Result = ctx.GetTable<Criteria.EntityType>().Where(LinqToSQLHelper.BuildWhereStatement(Criteria.StateBag), Criteria.StateBag.Values.ToArray()).Count() > 0;
        }
    }
}

Upvotes: 1

Views: 3159

Answers (2)

Mario
Mario

Reputation: 3455

You are looking to instantiate a generic type. Some info can be found here

This is a simple example demonstrating how to instantiate a List with a capacity of 3. Here is a method that you can call to create a generic when you don't know the type:

public static Object CreateGenericListOfType(Type typeGenericWillBe)
    {
        //alternative to the followin:
        //List<String> myList = new List<String>(3);


        //build parameters for the generic's constructor (obviously this code wouldn't work if you had different constructors for each potential type)
        object[] constructorArgs = new Object[1];
        constructorArgs[0] = 3;


        //instantiate the generic.  Same as calling the one line example (commented out) above. Results in a List<String> with 3 list items
        Type genericListType = typeof(List<>);
        Type[] typeArgs = { typeGenericWillBe };
        Type myNewGeneric = genericListType.MakeGenericType(typeArgs);
        object GenericOfType = Activator.CreateInstance(myNewGeneric, constructorArgs);


        return GenericOfType;
    }

And here is some sample code that will show you the example method works:

List<String> Strings = (List<String>)InstantiateGenericTypeWithReflection.CreateGenericListOfType(typeof(String));

        //demonstrate the object is actually a List<String> and we can do stuff like use linq extensions (isn't a good use of linq but serves as example)
        Strings.Add("frist");
        Strings.Add("2nd");
        Strings.Add("tird");
        Console.WriteLine("item index 2 value: " + Strings.Where(strings => strings == "2").First());

In your example, replace your GetTable<Criteria.EntityType>() with CreateGenericTableOfType(Criteria.EntityType). This will return a generic table of whatever type you pass in. You will of course need to implement the method properly (handle constructor args, change List to Table etc).

Upvotes: 2

Iridium
Iridium

Reputation: 23731

I think you need to change the way you're doing this slightly, and instead use generics instead of the EntityType property. Perhaps something along the lines of the following:

// Create an abstract class to be used as the base for classes that are supported by
// ExistsCommand and any other classes where you need a similar pattern
public abstract class ExtendedCriteria<T> : IGeneratedCriteria
{
    public ExistsCommand GetExistsCommand()
    {
        return new ExistsCommand<T>(this);
    }
}

// Make the non-generic ExistsCommand abstract
public abstract class ExistsCommand
{
    protected abstract void DataPortal_Execute();
}

// Create a generic sub-class of ExistsCommand with the type parameter used in the GetTable call
// where you were previously trying to use the EntityType property
public class ExistsCommand<T> : ExistsCommand
{
    protected override void DataPortal_Execute()
    {
        using (var ctx = new DC.ADRPDataContext())
        {
            Result = ctx.GetTable<T>().Where(LinqToSQLHelper.BuildWhereStatement(Criteria.StateBag), Criteria.StateBag.Values.ToArray()).Count() > 0;
        }
    }

}

// Derive the AccountCriteria from ExtendedCriteria<T> with T the entity type
public class AccountCriteria : ExtendedCriteria<DAL.Account>
{
    ...
}

Upvotes: 0

Related Questions