,

Database-First Using SqlMetal

So far this chapter has focused on a code-first approach for generating a local database. To reiterate, code-first is the recommended approach for developing on the phone. The database-first approach, however, can also be used, although it is not fully supported.

SqlMetal is a command-line tool used to generate an entity model from a database. SqlMetal is not fully compatible with Windows Phone, because the code it generates does not compile until some minor alterations are made to it.

SqlMetal generates a DataContext derived class and entities representing database tables. Associations are inferred from the foreign key relationships in the database.

SqlMetal can be launched via a Visual Studio Command Prompt by selecting Microsoft Visual Studio 2010/Visual Studio Tools/Visual Studio Command Prompt (2010) in the Windows Start menu.

In the following example, the database file has been downloaded from isolated storage, using the WP7 Isolated Storage Explorer, and placed in a directory called C:Unleashed. SqlMetal is provided with the database path, the name code file to output, and the namespace in which to place all generated classes (ignore line breaks):

C:Unleashed>SqlMetal C:UnleashedTwitter.sdf
               /code:C:UnleashedTwitterDataModel.cs
               /namespace:DanielVaughan.WPUnleashed.Examples

After the code file has been generated, it can be added to your project. But before it can be compiled, two constructors must be removed. The key to identifying the errant constructors is that they both accept an IDbConnection and resemble the methods shown in the following excerpt:

public Twitter(System.Data.IDbConnection connection)
    : base(connection, mappingSource)
{
    OnCreated();
}

public Twitter(
          System.Data.IDbConnection connection,
          System.Data.Linq.Mapping.MappingSource mappingSource) :
        base(connection, mappingSource)
{
    OnCreated();
}

An example of a generated code file is located in the downloadable sample code. The file is named TwitterDataModel_Generated_Unused.cs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.21.229