I want to expose the contents of a SQL database as an OData feed using WCF Data Service.
Everything works well as long as the SQL database schema is unchanged. Once a database table is added or altered the Entity model is out of date. Recompiling the data service is not an option as the schema can change several times a day.
I am defining a table data service:
public class TablesDataService
{
private static List<Table> _tables;
static TablesDataService()
{
_tables = new List<Table>();
// query the database and add a table entity model for each table
}
public IQueryable<Table> Tables
{
get { return _tables.AsQueryable<Table>(); }
}
}
which uses the following POCO to represent an individual table:
[DataServiceKey("Name")]
public class Table
{
public Table(string name)
{
Name = name;
}
public string Name { get; private set; }
}
The WCF Data Service uses for following class in WcfDataService.svc:
public class WcfDataService : DataService<TablesDataService>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
config.SetEntitySetAccessRule("Tables", EntitySetRights.All);
}
}
Because each table in the SQL database has a different set of columns, I am looking for a way to add properties to the Table class dynamically so it can represent the shape of the database table as it exists at the time of the query.
For example, assuming the database contains a table called Population, I'd like to be able to support the following OData query:
http://localhost/WcfDataService.svc/Tables('Population')?$filter=Code eq 'CA'
where Code is a char(2) column containing the US state codes.
So far, any attempts to use either an ExpandoObject (instead of the Table class) or having the Table class derive from DynamicObject have failed to create a workable OData feed, resulting the following 'Request Error':
The exception message is 'Internal Server Error. The type 'ServiceLibrary.Table' is not supported.'
with the stack trace showing the exception being thrown inside
System.Data.Services.Providers.ReflectionServiceProvider.BuildHierarchyForEntityType
Is there a way to create a Table class that exposes properties (representing the columns of the corresponding database table) dynamically that can be used 开发者_运维问答by a WCF Data Service to browse a SQL database?
The OData Provider Toolkit contains a sample implementation of a R/W Untyped Data Provider which can easily be modified to return metadata and table data.
精彩评论