As part of a profiling tool, I have a custom ADO.NET stack that acts as a "decorator" around standard ADO.NET, so it doesn't actually do any work - it just passes on the calls (but with logging, etc). Among other things, I have provided a DbProviderFactory from my custom connection that implements IServiceProvider and supplies a custom DbProviderServices.
This works great for most tools, including LINQ-to-SQL - however, Entity Framework is not happy.
For example - say I have:
MetadataWorkspace workspace = new MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { Assembly.GetExecutingAssembly() });
using(var conn = /* my custom wrapped DbConnection */)
{
var provider = DbProviderServices
.GetProviderServices(conn); // returns my custom DbProviderServices
var factory = DbProviderServices
.GetProviderFactory(conn); // returns my custom DbProviderFactory
...
so far so good - the above two lines work; the correct (custom) provider info is returned.
Now we can add an EF model:
using (var ec = new EntityConnection(workspace,conn))
using (var model = new Entities(ec))
{
count = model.Users.Count(); // BOOM!
}
fails with exception:
Unable to cast object of type '(my custom connection)' to type 'System.Data.SqlClient.SqlConnection'.
which is during assignment of a connection to a command; essentially, it has defaulted to the sql-server provider for the SSpace, and generated a naked SqlCommand. It is then trying to assign conn to the generated command, which can't work (it will work correctly if all the decorators are in place, and a decorated DbCommand was used instead).
Now, the whole point of wrapping this on the fly means I don't really want to