2013年1月16日星期三

Entity Framework For Html5 SQLite, PhoneGap Data Access Framework

Notice: The HTML5 SQLite library has been picked out from Nova PhoneGap Framework, so it is a standalone library now. The latest source code and documentation have been moved to github https://github.com/leotsai/html5sqlite
Nova PhoneGap Framework has developed a framework for data access in html5 SQLite. It works in a similar way with the C# EntityFramework (EF). See documentation
Take a look at the below code then you will know it's so easy to define your database and entities, and query, add, update, delete entities from the db.

// define dbContext & entities------------------------------------
var DemoDataContext = function () {
nova.data.DbContext.call(this, "Demo", style="color: #a31515">"1.0", "Demo DB", 1000000);

this.users = new nova.data.Repository( style="color: blue">this, User, "users");
this.roles = new nova.data.Repository( style="color: blue">this, Role, "roles");
};

DemoDataContext.prototype = new nova.data.DbContext();
DemoDataContext.constructor = DemoDataContext;

var User = function () {
nova.data.Entity.call( style="color: blue">this);
this.name = "";
this.password = "";
this.birthYear = 1980;
this.createdDate = new Date();
this.deleted = false;
};
User.prototype = new nova.data.Entity();
User.constructor = User;

var Role = function () {
nova.data.Entity.call( style="color: blue">this);
this.name = "";
this.createdDate = new Date();

};
Role.prototype = new nova.data.Entity();
Role.constructor = Role;
// end define dbContext & entities------------------------------------

// service methods----------------------------------------------------
function getAllUsers(callback) {
new DemoDataContext().users.toArray(function (users) {
alert(users.length);
callback(users);
});
}

function getUserByName(name, callback) {
new DemoDataContext().users.where("name='" + name + "'").toArray( style="color: blue">function (users) {
callback(users.firstOrDefault());
});
}

function addRole(roleName, callback) {
var role = new Role();
role.name = roleName;
var db = new DemoDataContext();
db.roles.add(role);
db.saveChanges(callback);
}

function updateUserPassword(username, password, callback) {
getUserByName(username, function (user) {
if (user == null) {
throw "no user found.";
}
user.password = password;
var db = new DemoDataContext();
db.users.update(user);
db.saveChanges(callback);
});
}

function deleteUserByName(name, callback) {
getUserByName(name, style="color: blue">function (user) {
if (user == null) {
throw "no user found.";
}
var db = new DemoDataContext();
db.users.remove(user);
db.saveChanges(callback);
});
}

// end service methods----------------------------------------------------