Tuesday 14 June 2011

Deploying an Entity Data Model

In the past few posts, you've seen how to create and modify an Entity Data Model (EDM). You've also looked at the XML behind the visual EDM to understand how the conceptual model in the application maps to the data in the data store.

You may recall that I mentioned in the first post how easy it is to change your applications data store without having to modify the application itself. So, here's how to do it.

By default, the Entity Data Model Wizard creates a model with the metadata embedded inside the application assembly. If you take a look in App.config or Web.config, you'll see the connection information as shown below.

<connectionStrings>

<add name="AdventureWorksEntities" connectionString="metadata=res://*/AWModel.csdl|res://*/AWModel.ssdl|res://*/AWModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=DemoBox\SQLExpress;Initial Catalog=AdventureWorks;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

</connectionStrings>

Note that the metadata is identified as being a resource in the assembly by using the res://* path.

This works fine for many applications; however, changes to the model then require changes to the assembly. For example, if your storage model changes (a not uncommon occurrence), you will need to update the model and redeploy the whole assembly. Because it's only likely to be the storage model and mapping sections of the .edmx file that change, not the conceptual model that the application is coded against, it's far easier to store the model externally to the assembly and only update and redeploy the model itself.

The Metadata Artifact Processing property of the model defines where the model is deployed to at build time.

EntityModelProperties

The default setting is Embed in Output Assembly, but you can change this to Copy to Output Directory to store the model outside of the assembly. Now when you build the application, you'll see the .cdsl, .ssdl, and .msl files created in the debug directory.

DebugDirectory

And the connection string is now updated to point to these external files.

<connectionStrings><add name="AdventureWorksEntities" connectionString="metadata=.\AWModel.csdl|.\AWModel.ssdl|.\AWModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=DemoBox\SQLExpress;Initial Catalog=AdventureWorks;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

So now if you change the model, you can simply rebuild the application and then copy the new model files to the production server without redeploying the assembly.

No comments: