views:

246

answers:

2

Hello,

I am using the entity framework model to query my database and have put in a few views that I would like to use that all have the same query parameters. Rather than write a big list of case-switch statements I am wondering how to do this programmatically by passing through the view object as a parameter to my main method. In sql I would do this like:

public void Tables(string TableName)
{
    using(EntityModel entity = new EntityModel()){
      string sql = "select * from " + TableName;
      etc....
}

However I just can't see how to do a similar thing with the entity framework model i.e.

public void Tables(Type TableName)
{
    using(EntityModel entity = new EntityModel()){
      ObjectQuery<Users> oq = new ObjectQuery<Users>("EntityModel.Users", EntityModel); 
      var q = (from p in oq select p);
}

That's fine if you know what type of table or view you need (i.e. Users), but you can't pass a type as a parameter because ObjectQuery can't accept variables, typeof() or anything that isn't hard-coded. Anyone have any ideas if this is at all possible?

A: 

You can do this with Entity SQL, but you would still need to know the return type of the query. If the query always returned the same type of entity, then I think you would not be passing in a "TableName." So what is it that you actually want out of the query? Some scalar value? Scalars, after all, are all you would get out of your SQL example. You can do that with Entity SQL, specify the entity set name as a string, and get scalar results back. See: http://msdn.microsoft.com/en-us/library/cc716751.aspx

Craig Stuntz
Thank you for taking the time to help
Alan
A: 

Use a generic method to pass the type

public void Tables<TTableType>(string TableName)
{
     using (EntityModel entity = new EntityModel())
     {
            ObjectQuery<TTableType> oq = new ObjectQuery<TTableType>("EntityModel." + TableName, entity);       
            var q = (from p in oq select p);
        }
    }
Coach David