Databases Reference
In-Depth Information
As you can see, the
UnleashedModelProvider
constructor receives the original
DataModelProvider
as a parameter. It takes the original
Tables
collection and creates a
new
UnleashedTableProvider
object for each
TableProvider
in it. This collection of
TableProvider
decorators is stored in the private field called
tables
and returned by the
overridden
Tables
property.
Replacing the Built-in DataModelProvider
Now that the
UnleashedModelProvider
that supports custom properties has been imple-
mented, all that's left to do is replace the built-in
DataModelProvider
Dynamic Data
creates by default.
Unfortunately, the built-in providers are internal to the
System.Web.DynamicData
assembly
and cannot be instantiated directly. However, the
MetaTable
class defines a property called
Provider
, which returns the built-in
TableProvider
and, through its
DataModel
property,
allows you to get a hold of the original
DataModelProvider
. The following code snippet
illustrates how this can be done:
var model = new MetaModel(false);
model.RegisterContext(typeof(NorthwindEntities));
DataModelProvider provider = model.Tables[0].Provider.DataModel;
Notice that this code creates a new
MetaModel
instance with
false
as the
registerGlobally
argument. Because you only need the original model provider, you don't want the next call
to the
RegisterContext
method to register the
NorthwindEntities
class in the global list of
models used by Dynamic Data and causing an exception when you try to register it again
with your custom model provider. Having a temporary
MetaModel
instance with the
NorthwindEntities
context registered, you can extract the original model provider from
the first
MetaTable
object in it.
Using the original provider object, you can create a new
UnleashedModelProvider
object
and register it globally and place this code directly in the
Global.asax
, next to the model
registration code. However, it definitely feels like a hack, and because the
UnleashedModel
already extends the built-in
MetaModel
class, this workaround can be hidden inside of it,
keeping the application code clean.
Listing 13.9 shows the source code of the
UnleashedMetaModel
class with a redefined
RegisterContext
method. Just like the built-in version, it takes
Type
and
ContextConfiguration
objects as parameters. However, instead of registering the context
directly, it creates a temporary
MetaModel
to obtain the original model provided and regis-
ters the context with the
UnleashedModelProvider
.
LISTING 13.9
UnleashedMetaModel Implementation with RegisterContext Method
using System;
using System.Web.DynamicData;
using System.Web.DynamicData.ModelProviders;
namespace Unleashed.DynamicData