Using an existing database with Azure mobile app service

Most samples for the azure mobile app server (on the new portal) are for start-from-scratch Todo item list….however what if you already have a database? Perhaps its used by a seperate Azure web app and now you want to add a native app to it.  This article will show the steps needed to make your database work with Azure Mobile Apps.

1) First step turn off EF database initialisation:
In your startup class comment out:

//Database.SetInitializer(new myappInitializer());

and add:

Database.SetInitializer<myappContext>(null);

This will stop entity framework from trying to overwrite data/structure in the database.

2) Modify the database:

Azure needs Id column on each table. If you primary key column has  a different name you will need to rename it. Also the datatype will need to be nvarchar.

3) Finally add in the models into your app service but leave out the Id column. This will be managed by Azure Mobile App service itself.

4) Add an InsertUpdateDelete trigger to each table that will be used by your TableControllers:

CREATE TRIGGER [dbo].[TR_dbo_TABLENAMEHERE_InsertUpdateDelete] ON [dbo].[TABLENAMEHERE] AFTER INSERT, UPDATE, DELETE AS BEGIN UPDATE [dbo].[TABLENAMEHERE] SET [dbo].[TABLENAMEHERE].[UpdatedAt] = CONVERT(DATETIMEOFFSET, SYSUTCDATETIME()) FROM INSERTED WHERE inserted.[Id] = [dbo].[TABLENAMEHERE].[Id] END

All done!