Native Object to Dynamic Object
Native
objects in runtime can be converted to dynamic objects
Note: requires DB with established connection
public void NativeToDynamic()
{
DB db = null;
try
{
const string db_name = "Test";
db = new
DB("server=(local);password=;options=none;");
db.DeleteDatabase(db_name, true);
db.CreateDatabase(db_name);
db.OpenDatabase(db_name);
Book
book = new Book()
{
DbID = 12345,
Edition = -33,
Price = 776.32F,
IBSN = "7748-3782-38768-23343",
Publisher = "Publisher Mublisher",
Title = "Title
Mitle",
YearPublished = new DateTime(356,
2, 2),
};
Dynamic
dynObj = new Dynamic(book);
Assert.AreEqual(book.DbID,
(long)dynObj["DbID"]);
Assert.AreEqual(book.Edition,
(int)dynObj["Edition"]);
Assert.AreEqual(book.Price,
(float)dynObj["Price"]);
Assert.AreEqual(book.IBSN,
(string)dynObj["IBSN"]);
Assert.AreEqual(book.Publisher,
(string)dynObj["Publisher"]);
Assert.AreEqual(book.Title,
(string)dynObj["Title"]);
Assert.AreEqual(book.YearPublished,
(DateTime)dynObj["YearPublished"]);
}
finally {
db.Close(); }
}
Some time it is
necessary to update existing Dynamic, this could be done using FromNative method. This could be handy since the rule of thumb
is to use native types to work with the objects and use Dynamic to store the
data.
//Establish
connection
DB db = new DB("server=(local);password=pwd;options=;");
//Create the
database
db.DeleteDatabase(DBName, true);
db.CreateDatabase(DBName);
//Open existing
database
db.OpenDatabase(DBName);
var @do = new Dynamic();
@do["Name"]
= "John";
db.Store(@do);
//get object
back
@do = db.Query<Dynamic>().Where(x => x["Name"] == "John").First();
//convert to
native
var user =
@do.ToNative<MyUser>();
//update native
object
user.Name = "Frank";
//updates
existing DO from the native object
@do.FromNative(user);
//update DO
db.Store(@do);
db.Close();