A Schema Abstraction Example
Now that you have had a chance to see how to use the EDM model, let's revisit the name-change scenario discussed at the beginning of this article, using an example that illustrates how useful EDM is in abstracting the database schema from your applications. Begin by making a small change to the database to recreate the scenario; rename the
Name column in the
ProductSubcategory table to
ProductSubcategoryName in the AdventureWorks database. After making the change, when you run the application, you'll get an expected runtime exception:
<span class="pf">"{"Invalid column name 'Name'."}"</span>
Normally, fixing such a breaking change would require you to find every place in your code that accessed that database field, changing code to match the new name. But using the EDM model, all you need to do is to fix this error is open the XML mapping files and make the corresponding changesthere's no need to touch the application code. Specifically, you need to make two changes:
First, open the
AdventureWorksModel.Target.ssdl file and find the
<Property> node line under the
<EntityType> node that has a
Name="ProductSubcategory" attribute:
<Property Name="Name" Type="nvarchar" Nullable="false"
MaxLength="50" />
Change it to reference the new field name as shown below:
<Property Name="ProductSubcategoryName" Type="nvarchar"
Nullable="false" MaxLength="50" />
Second, in the
AdventureWorksModel.cs.msl file, find the
<p1:ScalarProperty> node shown below (you'll find it under the node
<EntitySetMapping>||<EntityTypeMapping>||<TableMappingFormat> that has the
TableName="ProductSubcategory" attribute):
<p1:ScalarProperty p1:Name="Name" p1:ColumnName="Name" />
Change it to:
<p1:ScalarProperty p1:Name="Name"
p1:ColumnName="ProductSubcategoryName" />
Save your changes. Now if you run the application again, it should work just fine. As you can see, you have accommodated the change in the database schema by changing only the mapping fileswithout having to touch a single line of code in the client application itself.
So, as you've seen, not only does using the Entity Data Model and Entity SQL let you make database queries using an application and object-centric approach, it also isolates your application from database schema changes that would otherwise require code changes.
This article discussed the basics of ADO.NET vNext Framework and showed how to create simple EDM models through the EDM designer. You also saw some examples of using the mapping provider and Entity SQL to execute queries against the EDM model. These tools simplify and isolate your application's interactions with databasesfreeing you to focus on the core business logic of the application. The next installments in this series will build on the basics and discuss the advanced features of ADO.NET vNext.