Data Platform Developer Center > Data Platform Development Forums > LINQ to SQL > Going from the mapping domain back to the DataContext domain
Ask a questionAsk a question
 

AnswerGoing from the mapping domain back to the DataContext domain

  • Friday, October 16, 2009 3:50 PMrafsots Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi there:

    Suppose I have a DataContext with several entity tables, suppose I am given a tableName and a key,

    I want to get the entity table to be able to perform a linq query like EntityTable.Where(d => d.Key == Key), but without having to code a switch statement like:

                  switch (tableName)
                  {
                     case "Customers":
                        return db.Customers.Where(c => c.key == key).Select(c => c).FirstOrDefault();
                        break;

                     case...
                  }

    But, something like this instead:

                  return GetEntityTable(tableName).Where(c => c.key == key).Select(c => c).FirstOrDefault();

    Note: I suppose I have to use the Mapping information, but once I get the mapped table, I don't know how to get back to the DataContext domain to perform the query.

    Thanks in advance,

    Rafael


    Believe you can do it, and you will!!

Answers

  • Wednesday, October 21, 2009 2:58 AMKristoferA - Huagati SystemsAnswererUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    But, something like this instead:

                  return GetEntityTable(tableName).Where(c => c.key == key).Select(c => c).FirstOrDefault();

    Note: I suppose I have to use the Mapping information, but once I get the mapped table, I don't know how to get back to the DataContext domain to perform the query.


    Two steps:

    1) To get hold of a ITable/IQueryable for a table by table name, you can use the datacontext's mapping member; it lets you explore all entities and how they are mapped. An extension method like this:

    public static Type GetEntityTypeFromTableName(this DataContext dc, string qualifiedTableName)
    {
        MetaTable table = dc.Mapping.GetTables().Where(t => t.TableName.Equals(qualifiedTableName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        if (table != null)
        {
            return table.RowType.Type;
        }
        else
        {
            throw new ArgumentException("Invalid table name.");
        }
    }
    

    ...will allow you to do sometihng like this:

    IQueryable empQuery = dc.GetTable(dc.GetEntityTypeFromTableName("HumanResources.Employee"));
    

    ...note that "qualifiedTableName may need to use brackets around the schema and/or table name; reserved keywords, table names with special characters etc are bracketed by L2S...



    2) Since the above give us a ITable/IQueryable of unknown generic type, we can't go loose on it with lambdas without casting it to its' generic type. We can however pass it to the dynamic linq library (System.Linq.Dynamic) and append the where clause, projections, sorting etc using the extension methods in System.Linq.Dynamic... Check out http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx


    Kristofer - Huagati Systems Co., Ltd. - Cool tools for Linq-to-SQL and Entity Framework: www.huagati.com/dbmltools (VS designer add-in), www.huagati.com/L2SProfiler (query profiler for L2S)
    • Marked As Answer byrafsots Wednesday, October 21, 2009 4:00 PM
    •  
  • Thursday, October 22, 2009 1:17 AMHuagati Systems Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    It worked, the problem is that one can't get a complete entity out of Dinamic Linq, just a projection, like "new(Name, Address...)", the existing documentation of Dinamic Linq doesn't say anything about obtaining a whole entity.

    Use .Select("it") to get the entity itself, instead of a projection...
    • Marked As Answer byrafsots Friday, October 23, 2009 2:51 AM
    •  

All Replies

  • Tuesday, October 20, 2009 6:31 AMYichun_FengMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi Rafael,

    Could you try to use entity sql to query?

    using (ObjectContext oc = new ObjectContext(myConnectionString, "NorthwindContainer")) {

        oc.Connection.Open();

        string myQuery = "SELECT VALUE c.CategoryName FROM Categories as c";

        foreach (string s in new ObjectQuery<string>(myQuery, oc)) {

            Console.WriteLine(s);

        }

    }

    There are more samples in this blog,
    http://blogs.msdn.com/adonet/archive/2007/05/30/entitysql.aspx

    Does this work for you?


    Best Regards
    Yichun Feng



    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
  • Tuesday, October 20, 2009 12:09 PMrafsots Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Thanks Yichun_Feng for answering:

    What I need is to be able to iterate through the entity tables of a DataContext, and not iterating through the values of a specific column.

    I learned to iterate through the members of an entity table using the linq mapping namespace, but now I need to do the same with the entity tables. I'm not quite sure that it can be done...

    Rafael


    Believe you can do it, and you will!!
  • Wednesday, October 21, 2009 2:36 AMYichun_FengMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi rafsots,

    Since the query is string, you can build any type you want. For example,

    "SELECT VALUE c.CategoryName FROM " + tablename + " as c"

    Does this works for you?


    Best Regards
    Yichun Feng


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
  • Wednesday, October 21, 2009 2:58 AMKristoferA - Huagati SystemsAnswererUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    But, something like this instead:

                  return GetEntityTable(tableName).Where(c => c.key == key).Select(c => c).FirstOrDefault();

    Note: I suppose I have to use the Mapping information, but once I get the mapped table, I don't know how to get back to the DataContext domain to perform the query.


    Two steps:

    1) To get hold of a ITable/IQueryable for a table by table name, you can use the datacontext's mapping member; it lets you explore all entities and how they are mapped. An extension method like this:

    public static Type GetEntityTypeFromTableName(this DataContext dc, string qualifiedTableName)
    {
        MetaTable table = dc.Mapping.GetTables().Where(t => t.TableName.Equals(qualifiedTableName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        if (table != null)
        {
            return table.RowType.Type;
        }
        else
        {
            throw new ArgumentException("Invalid table name.");
        }
    }
    

    ...will allow you to do sometihng like this:

    IQueryable empQuery = dc.GetTable(dc.GetEntityTypeFromTableName("HumanResources.Employee"));
    

    ...note that "qualifiedTableName may need to use brackets around the schema and/or table name; reserved keywords, table names with special characters etc are bracketed by L2S...



    2) Since the above give us a ITable/IQueryable of unknown generic type, we can't go loose on it with lambdas without casting it to its' generic type. We can however pass it to the dynamic linq library (System.Linq.Dynamic) and append the where clause, projections, sorting etc using the extension methods in System.Linq.Dynamic... Check out http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx


    Kristofer - Huagati Systems Co., Ltd. - Cool tools for Linq-to-SQL and Entity Framework: www.huagati.com/dbmltools (VS designer add-in), www.huagati.com/L2SProfiler (query profiler for L2S)
    • Marked As Answer byrafsots Wednesday, October 21, 2009 4:00 PM
    •  
  • Wednesday, October 21, 2009 4:03 PMrafsots Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi KristoferA:

    Thanks for answering, it worked great!


    Believe you can do it, and you will!!
  • Wednesday, October 21, 2009 7:23 PMrafsots Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi KristoferA:

    It worked, the problem is that one can't get a complete entity out of Dinamic Linq, just a projection, like "new(Name, Address...)", the existing documentation of Dinamic Linq doesn't say anything about obtaining a whole entity.

    However, this Dinamic Linq could be handy when sending queries over a network, since it's a limitation of Linq.

    If you know a way of getting a whole entity, not just a projection, I appreciate you send a message...

    Rafael.
    Believe you can do it, and you will!!
  • Thursday, October 22, 2009 1:17 AMHuagati Systems Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    It worked, the problem is that one can't get a complete entity out of Dinamic Linq, just a projection, like "new(Name, Address...)", the existing documentation of Dinamic Linq doesn't say anything about obtaining a whole entity.

    Use .Select("it") to get the entity itself, instead of a projection...
    • Marked As Answer byrafsots Friday, October 23, 2009 2:51 AM
    •  
  • Saturday, October 31, 2009 4:38 AMDevaang25 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hello,

    I need to implement this exact functionality because I have different pages but with same UI and functionality and different tables

    I got the type by giving table name as a input but I dont know ahead also it is suggested but I cant do. some thing like

    I want to use query like below query where Customer would be replaced with unknown table type.
    public IQueryable<Customer> GetCustomerByID(
        int customerID)
    {
        return
            from cust in Context.Customer
            where cust.CustomerID == customerID
            select cust;
    }

     


    I dont know How to get table properties and fields by casting it to type which one is passing to the method.
  • Tuesday, November 03, 2009 7:13 AMDevaang25 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    HI,

    Yet my query is unsolved, Can anybody help me out in it??
  • Tuesday, November 03, 2009 8:54 AMKristoferA - Huagati SystemsAnswererUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hello,

    I need to implement this exact functionality because I have different pages but with same UI and functionality and different tables

    I got the type by giving table name as a input but I dont know ahead also it is suggested but I cant do. some thing like

    I want to use query like below query where Customer would be replaced with unknown table type.
    public IQueryable<Customer> GetCustomerByID(
        int customerID)
    {
        return
            from cust in Context.Customer
            where cust.CustomerID == customerID
            select cust;
    }

     


    I dont know How to get table properties and fields by casting it to type which one is passing to the method.

    Take a look at System.Linq.Dynamic - it allows you to build linq queries from strings:
    http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx


    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for Visual Studio 2008's L2S and EF designers)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
  • Friday, November 06, 2009 12:26 PMDevaang25 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hello ,

    May be it would be very easy but I cant get it.

    IQueryable

    empQuery = this.Context.GetTable(GenericClass1.GetEntityTypeFromTableName(this.Context, "dbo.PT_AdjustmentTypeCodes"));

     

    foreach (var item in empQuery)

    {

     

    }

    Now here I want to convert item to dbo.PT_AdjustmentTypeCodes

    is it possible??