Wednesday, 30 December 2015

How to Move EF Database First Template .tt File to Another Project

On this post, we will see how to have Entity Framework .tt template file generated by an .edmx file in a different project. By default .tt files are created under the same project where the .edmx file is. Usually this is our data layer project. However, for most of the time, we would want the POCO models that are generated by a model .tt file to be put under a separate project (i.e. domain or model project) for a better practice.

There are a few steps to make this happen (I am using VS 2013 here):
1. Add a new model template .tt file in the other project through 'add a new item' then select EF DbContext Generator file type under 'Data'.


2. Open the new .tt file then change the value of 'inputFile' to point to the .edmx file in the original project.

In this case, my data project is called 'MySolution.Data.StudentBoundedContext'.

3. To ensure that all of the to be be generated POCO classes have right namespaces, we need to tell the template file the new namespace to use. Right click the .tt file and select 'Properties' then put the new namespace on 'Custom Tool Namespace' value.


4. Delete the model .tt file on the original project.

5. I prefer to leave the context .Context.tt template file on the data layer project and only move the model .tt file to a domain/model project. Therefore, I will need to tell the context template file to refer to the models in the other project.
To do this:
- add a project reference to the other project (domain/model project)
- open the .Context.tt file and add a 'using' statement referring to the models namespace


6. Regenerate the models and context files by right clicking the template files and selecting 'Run Custom Tool'.

Monday, 14 December 2015

Bulk Insert in Web SQL

Below is a snippet of how to do bulk insert of records in Web SQL:
// db is the database object that is usually initialise with openDatabase() function
db.transaction(function (tx) {  
  // insert each record
  $.each(myArray, function (i, item) {
   tx.executeSql("INSERT INTO MyTable(name, value) VALUES (?, ?)", [item.name, item.value]);
  });   
},
// error
function (error) {
 . . .
},
// success - the transaction() function does not pass any object to its success callback
function () {
 . . .
});

Web SQL does not understand the Standard SQL bulk insert syntax such as
Insert Into tbl (col1, col2) Values ('val1', 'val2'), ('val3', 'val4'), ...
but each insert statement needs to be executed using executeSql() function. A transaction is usually used to wrap these insert commands.