Back to basics: POCO and One to Many relationships (and db4o)
augustus 17, 2010
Here is another back to basics post. Howto ‘do’ one-to-many when you are not having a RDBM and using POCO?
Here is the (very simple) model:
For persistance I use Db4o in this example. Please see this blogpost.
One blogentry has many comments. So, we’ll put comments in a List as a attribute of blogentry:
[csharp]
public class BlogEntry
{
public string blogtitle { get; set; }
public string blogstory { get; set; }
public DateTime postdate { get; set; }
public List<Comment> comments { get; set; }
public BlogEntry()
{
this.postdate = DateTime.Now;
}
}
[/csharp]
Here is the comment class:
[csharp]
public class Comment
{
public string commenttext { get; set; }
public string email { get; set; }
public BlogEntry blogentry { get; set; }
}
[/csharp]
Now we are ready to build our console based blog application:
[csharp]
static void Main(string[] args)
{
using (var s = SessionFactory.Current)
{
//DELETE
//s.DeleteAll<Comment>();
//s.DeleteAll<BlogEntry>();
//ADD
var b = new BlogEntry { blogtitle = "Lady Gaga FTW",
blogstory = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book"
};
var c = new Comment { blogentry = b, commenttext = "inderdaad", email = "info@test.com" };
var d = new Comment { blogentry = b, commenttext = "niet mee eens", email = "info@krap.com" };
List<Comment> commentlist = new List<Comment>();
commentlist.Add(c);
commentlist.Add(d);
b.comments = commentlist;
s.Save(b);
s.CommitChanges();
//RETRIEVE (2 foreach loops)
var blog = s.All<BlogEntry>();
foreach (BlogEntry ble in blog) {
Console.WriteLine(ble.blogtitle);
Console.WriteLine(ble.blogstory);
Console.WriteLine(ble.postdate);
foreach (Comment cmt in ble.comments)
{
Console.WriteLine("Comment: ");
Console.WriteLine(cmt.commenttext);
Console.WriteLine(cmt.email);
Console.WriteLine("—");
}
Console.WriteLine("########");
}
}
[/csharp]
So, when I execute this application a few times, the db40 file gets a bit stuffed and I get the following output, which is a full blown console blog application:
Hmm.
Oh well, I said it was a back to basics post, didn’t I. š
Thanks for sharing! This is a nice example for db4o beginners =)
See: http://developer.db4o.com/Blogs/Community/tabid/166/entryid/938/db4o-and-ASP-NET-MVC-2.aspx
Best!!
German
Thanks for mentioning us at the Db4o forum! Very much appreciated.
Possibly the BEST post that I read in my life =D
Kindest Regards
Gilbert
Awesome site, I hadn’t come across http://www.thebuttonfactory.nl before during my searches!
Carry on the good work!
I like reading your blog for the reason that you can constantly bring us new and cool things, I feel that I should at least say thanks for your hard work.
– Henry