Samples - folkelib/Folke.Elm GitHub Wiki
A dd a connection string into the app.config or web.config file of your application. For instance:
<connectionStrings>
<add name="elm" providerName="MySql.Data.MySqlClient" connectionString="Server=localhost;Database=folke;Uid=folke;Pwd=test;" />
</connectionStrings>
Then in your code create a database context object (called session
below) through a database driver and a mapper (the mapper will hold the mappings between the classes and the database tables). We use MySql in the example below:
var session = new FolkeConnection(new MySqlDriver(), new Mapper(), ConfigurationManager.ConnectionStrings["elm"].ConnectionString);
session
is now your database context object.
Simply point to any class in your assembly and the ORM will automatically build the tables of every class in the assembly. For instance, if you use Folke.AspNet.Identity you simply need the code below:
session.UpdateSchema(typeof(RoleUser).Assembly);
Any other class of the namespace would have the same effect.
It's very easy to save objects to the database. Since the database context is Disposable it's recommended to proceed in a using()
statement to make sure the session is automatically disposed when done. Let's create a "Ian Banks" author.
using(var transaction = session.BeginTransaction()){
Author author = new Author();
author.FirstName = "Ian";
author.LastName = "Banks";
session.Save(author);
transaction.Commit();
}
Elm will return an object of the specified class with the provided id
. For instance for a "Book" object:
Book myBook = session.Load<Book>(id);
The Load()
method will throw an error if the id doesn't exist. If you need a null to be returned, use Get()
:
Book myBook = session.Get<Book>(id);
You can of course send more complex queries with WHERE or JOIN clauses. Let's return all the books from Ian Banks that we created before.
var books = session.SelectAllFrom<Book>()
.Where(x => x.Author == author)
.ToList();
foreach(var book in books){
console.WriteLine(book.Title);
}