How I can define custom instance logic of data model in ADO.NET Data Services?

When we work with ADO.NET Data Services we reference data model via generic-parameter. Thus, instance of data context class it is created by infrastructure of ADO.NET Data Services. In this case ADO.NET Data Services use constructor without parameters.

Frequently such behavior quite enough – we create data model, in configuration file we register connection string and it works. However, it is possible to see scenarios when it necessary to meddle in this process.

Causes my be very different:

  • We need to store connection string outside of configuration file;
  • We need to create not DataContext class, but his class, which has been inherited from this;
  • Data Context class not contains constructor without parameters (yes, yes, and such too happens);
  • etc
  • etc

In this cases ADO.NET Data Services platform offer us very nice way to solve this problem. Everything, that it is necessary to make is to override method CreateDataSource() of base class.

 

public class WebDataService1 : DataService<DataClasses1DataContext>
{
    public static void InitializeService(IDataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    }
 
     protected override DataClasses1DataContext CreateDataSource()
    {
        return base.CreateDataSource();
    }
}

As you can see, this method returns a data source of that type, which is specified in generic-parameter when we define service class. This method called when it is necessary to get data model. Now we can define custom logic, in which we are needing. For example, we can redefine connection string:

public class WebDataService1 : DataService<DataClasses1DataContext>
{
    public static void InitializeService(IDataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    }
 
    protected override DataClasses1DataContext CreateDataSource()
    {
        return new DataClasses1DataContext("some connection string");
    }
}

No Comments