Search code examples
c#silverlightlinq-to-entitieswcf-ria-services

get column names of a table from database in silverlight


how do i get column names of a table from database in domain service of the silverlight application and then use these in the listbox for client to select . i looked through here LINQ Query to get Column Headers in Silverlight but 't was little confusing .

As far as I know in Silverlight u write domain service to reach the data in the server side and silverlight creates the context in the client side and u use context there .So i assumed i need a datacontext and i created one in the server side which reaches the same database and i used that context in my method as the link above but this time there was an exception like "System.ArgumentException was unhandled by user code" and " Message=Keyword not supported: 'metadata'." i cant use System.Data.Linq inn the client side so i can use that method in the client side neither

i am writing this method in the domain service inherited from LinqToEntitiesDomainService class.I am really stuck at this point.

All answers will be appreciated.


Solution

  • There is no built in support for this. However, you can use the following SQL to get the columns from a table. In this example, there is a table named Foo.Bar where Foo is the schema.

    SELECT c.name
    FROM sys.objects o
    JOIN sys.columns c
        ON o.object_id = c.object_id
    JOIN sys.schemas s
        ON o.schema_id = s.schema_id
    WHERE
        s.name = 'Foo'
        AND o.name = 'Bar'
    

    I am using an Entity Framework DbContext to get the results.

    var commandText = "<SQL from above>";
    var contextAdapter = (IObjectContextAdapter) this;
    IEnumerable<string> columnNames = contextAdapter.ObjectContext.ExecuteStoreQuery<string>(commandText);
    

    You can then add an invoke method to your DomainService.

    [Invoke] // Use invoke for non-entities
    public string[] GetColumnNames(string table)
    {
        // Format the SQL and get the results;
        return columnNames.ToArray();
    }