I am developing a bookmark system in ASP.NET MVC and I use NHibernate to
query the database.
I have a many to many relationship:
- A bookmark can have many tags
- A tag can have many bookmarks
Models:
public class Bookmark{
public virtual string Title { get; set; }
public virtual string Link { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Tag> Tags { get; set; }}
public class Tag{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Bookmark> Bookmarks { get; set; }}
I want to get a tag, loop trough its bookmarks, and for each bookmark loop
trough its tags. To do this I used this:
public Tag GetTagByTitle(string username, string title){
ICriteria criteriaQuery = SessionFactory.GetCurrentSession()
.CreateCriteria(typeof(Tag))
.SetFetchMode("Bookmarks", FetchMode.Eager)
.CreateAlias("User", "User")
.Add(Restrictions.Eq("Title", title))
.Add(Restrictions.Eq("User.Username", username));
IList<Tag> tags = criteriaQuery.List<Tag>();
Tag tag = tags.FirstOrDefault();
return tag;}
This gives me a tag with its bookmarks. However for each bookmark it is
doing another query automatically to obtain its tags (lazy loading?). So if
I have 10 bookmarks I get 1 + 10 queries. Is it possible to do this with
one or two queries?
Example with NHibernate Profiler (3 bookmarks):
[image: Example with NHibernate Profiler (3 bookmarks)]
--
You received this message because you are subscribed to the Google Groups
"nhusers" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/nhusers.
For more options, visit https://groups.google.com/groups/opt_out.