tags:

views:

246

answers:

2

Hi Guys, I don't know if I am doing something wrong "I think I am" or I have hit a subsonic limitation. I have 3 tables Articles, ArticleCategories and ArticleComments with a one to many relationship between Articles the other tables. I have created the following class

  public partial class Article
{
    private string _CategoryName;
    public string CategoryName
    {
        get { return _CategoryName; }
        set
        {
            _CategoryName = value;
        }

    }
    public ArticleCategory Category { get;set;}
    private List<System.Linq.IQueryable<ArticleComment>> _Comments;
    public List<System.Linq.IQueryable<ArticleComment>> Comments
    {
        get
        {
            if (_Comments == null)
                _Comments = new List<IQueryable<ArticleComment>>();
            return _Comments;
        }
        set
        {
            _Comments = value;
        }
    }

}

I get a collection of articles using this snippet

var list = new IMBDB().Select.From<Article>()
             .InnerJoin<ArticleCategory>(ArticlesTable.CategoryIDColumn, ArticleCategoriesTable.IDColumn)
             .InnerJoin<ArticleComment>(ArticlesTable.ArticleIDColumn,ArticleCommentsTable.ArticleIDColumn)
             .Where(ArticleCategoriesTable.DescriptionColumn).IsEqualTo(category).ExecuteTypedList<Article>();

            list.ForEach(x=>x.CategoryName=category);

            list.ForEach(y => y.Comments.AddRange(list.Select(z => z.ArticleComments)));

I get the collection Ok but when I try to use the comments collection using

  foreach (IMB.Data.Article item in Model)

{

       %>

<%=item.ArticleID %> <%=item.CategoryName %>

<%=item.Subject %>

  <%
      foreach (IMB.Data.ArticleComment comment in item.Comments)
      {

          %>
         ***<%=comment.Comment %>*** 
      <%}
   } %>

the comment.Comment line throws this exception Unable to cast object of type 'SubSonic.Linq.Structure.Query`1[IMB.Data.ArticleComment]' to type 'IMB.Data.ArticleComment'.

I am basically trying to avoid hitting the database each time the comment is needed. is there another to achieve this? Thanks

+1  A: 

Hi Sammy - first thought, shouldn't the category association be the other way around? Category has many Articles? I don't know if that will help here - it's my first observation.

I think you're having a naming collision here. A "Structure.Query" is an object we create on the Structs.tt and it looks like that's the namespace you're referencing somehow with "item.Comments". My guess is there's a table somewhere called "Comments" that is getting confused.

Can you open up the Article class and look at the return of "Comments" property to make sure it's returning a type, and not the query?

Rob Conery
Rob you are correct about the relationship between categories and Articles.I still cant get the Category object "I checked the return type and its the correct type".I still get the Article.Category as null. The same code works fine in subsonic 2.1
Sammy
+1  A: 

OK - I'm not doing exactly what you're attempting but hopefully this example will bring some clarity to the situation. This is more along the lines of how I would do a join using SubSonic if I absolutely had to do it this way. The only way I would consider this approach is if I were confined by some 3rd party implementation of the object and/or database schema...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using SubSonic.Repository;

namespace SubsonicOneToManyRelationshipChildObjects
{
    public static class Program
    {
        private static readonly SimpleRepository Repository;

        static Program()
        {
            try
            {
                Repository = new SimpleRepository("SubsonicOneToManyRelationshipChildObjects.Properties.Settings.StackOverflow", SimpleRepositoryOptions.RunMigrations);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }

        public class Article
        {

            public int Id { get; set; }
            public string Name { get; set; }

            private ArticleCategory category;
            public ArticleCategory Category
            {
                get { return category ?? (category = Repository.Single<ArticleCategory>(single => single.Id == ArticleCategoryId)); }
            }

            public int ArticleCategoryId { get; set; }

            private List<ArticleComment> comments;
            public List<ArticleComment> Comments
            {
                get { return comments ?? (comments = Repository.Find<ArticleComment>(comment => comment.ArticleId == Id).ToList()); }
            }
        }

        public class ArticleCategory
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        public class ArticleComment
        {
            public int Id { get; set; }
            public string Name { get; set; }

            public string Body { get; set; }

            public int ArticleId { get; set; }
        }

        public static void Main(string[] args)
        {
            try
            {
                // generate database schema
                Repository.Single<ArticleCategory>(entity => entity.Name == "Schema Update");
                Repository.Single<ArticleComment>(entity => entity.Name == "Schema Update");
                Repository.Single<Article>(entity => entity.Name == "Schema Update");

                var category1 = new ArticleCategory { Name = "ArticleCategory 1"};
                var category2 = new ArticleCategory { Name = "ArticleCategory 2"};
                var category3 = new ArticleCategory { Name = "ArticleCategory 3"};

                // clear/populate the database
                Repository.DeleteMany((ArticleCategory entity) => true);
                var cat1Id = Convert.ToInt32(Repository.Add(category1));
                var cat2Id = Convert.ToInt32(Repository.Add(category2));
                var cat3Id = Convert.ToInt32(Repository.Add(category3));

                Repository.DeleteMany((Article entity) => true);
                var article1 = new Article { Name = "Article 1", ArticleCategoryId = cat1Id };
                var article2 = new Article { Name = "Article 2", ArticleCategoryId = cat2Id };
                var article3 = new Article { Name = "Article 3", ArticleCategoryId = cat3Id };

                var art1Id = Convert.ToInt32(Repository.Add(article1));
                var art2Id = Convert.ToInt32(Repository.Add(article2));
                var art3Id = Convert.ToInt32(Repository.Add(article3));

                Repository.DeleteMany((ArticleComment entity) => true);
                var comment1 = new ArticleComment { Body = "This is comment 1", Name = "Comment1", ArticleId = art1Id };
                var comment2 = new ArticleComment { Body = "This is comment 2", Name = "Comment2", ArticleId = art1Id };
                var comment3 = new ArticleComment { Body = "This is comment 3", Name = "Comment3", ArticleId = art1Id };
                var comment4 = new ArticleComment { Body = "This is comment 4", Name = "Comment4", ArticleId = art2Id };
                var comment5 = new ArticleComment { Body = "This is comment 5", Name = "Comment5", ArticleId = art2Id };
                var comment6 = new ArticleComment { Body = "This is comment 6", Name = "Comment6", ArticleId = art2Id };
                var comment7 = new ArticleComment { Body = "This is comment 7", Name = "Comment7", ArticleId = art3Id };
                var comment8 = new ArticleComment { Body = "This is comment 8", Name = "Comment8", ArticleId = art3Id };
                var comment9 = new ArticleComment { Body = "This is comment 9", Name = "Comment9", ArticleId = art3Id };
                Repository.Add(comment1);
                Repository.Add(comment2);
                Repository.Add(comment3);
                Repository.Add(comment4);
                Repository.Add(comment5);
                Repository.Add(comment6);
                Repository.Add(comment7);
                Repository.Add(comment8);
                Repository.Add(comment9);

                // verify the database generation
                Debug.Assert(Repository.All<Article>().Count() == 3);
                Debug.Assert(Repository.All<ArticleCategory>().Count() == 3);
                Debug.Assert(Repository.All<ArticleComment>().Count() == 9);

                // fetch a master list of articles from the database
                var articles = 
                    (from article in Repository.All<Article>() 
                    join category in Repository.All<ArticleCategory>() 
                        on article.ArticleCategoryId equals category.Id 
                    join comment in Repository.All<ArticleComment>() 
                        on article.Id equals comment.ArticleId 
                    select article)
                    .Distinct()
                    .ToList();

                foreach (var article in articles)
                {
                    Console.WriteLine(article.Name  + " ID " + article.Id);
                    Console.WriteLine("\t" + article.Category.Name + " ID " + article.Category.Id);

                    foreach (var articleComment in article.Comments)
                    {
                        Console.WriteLine("\t\t" + articleComment.Name + " ID " + articleComment.Id);
                        Console.WriteLine("\t\t\t" + articleComment.Body);
                    }
                }

                // OUTPUT (ID will vary as autoincrement SQL index

                //Article 1 ID 28
                //        ArticleCategory 1 ID 41
                //                Comment1 ID 100
                //                        This is comment 1
                //                Comment2 ID 101
                //                        This is comment 2
                //                Comment3 ID 102
                //                        This is comment 3
                //Article 2 ID 29
                //        ArticleCategory 2 ID 42
                //                Comment4 ID 103
                //                        This is comment 4
                //                Comment5 ID 104
                //                        This is comment 5
                //                Comment6 ID 105
                //                        This is comment 6
                //Article 3 ID 30
                //        ArticleCategory 3 ID 43
                //                Comment7 ID 106
                //                        This is comment 7
                //                Comment8 ID 107
                //                        This is comment 8
                //                Comment9 ID 108
                //                        This is comment 9         

                Console.ReadLine();

                // BETTER WAY (imho)...(joins aren't needed thus freeing up SQL overhead)

                // fetch a master list of articles from the database
                articles = Repository.All<Article>().ToList();

                foreach (var article in articles)
                {
                    Console.WriteLine(article.Name + " ID " + article.Id);
                    Console.WriteLine("\t" + article.Category.Name + " ID " + article.Category.Id);

                    foreach (var articleComment in article.Comments)
                    {
                        Console.WriteLine("\t\t" + articleComment.Name + " ID " + articleComment.Id);
                        Console.WriteLine("\t\t\t" + articleComment.Body);
                    }
                }

                Console.ReadLine();

                // OUTPUT should be identicle
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }
    }
}

The following is my personal opinion and conjecture and can be tossed/used as you see fit...

If you look at the "Better way" example this is more along the lines of how I actually use SubSonic.

SubSonic is based on some simple principles such as

  • Each table is an object (class)
  • Each object instance has an Id (e.g. Article.Id)
  • Each object should have a Name (or similar)

Now if you write your data entities (your classes that are representations of your tables) in a manner that makes sense when you use SubSonic you're going to work well together as a team. I don't really do any joins when I work with SubSonic because I typically don't need to and I don't want the overhead. You start to show a good practice of "lazy-loading" the comment list property on your article object. This is good, this means if we need the comments in the consumer code, go get-em. If we don't need the comments, don't spend the time & money to go fetch them from the database. I restructured your ArticleCategory to Article relationship in a way that makes sense to me but may not suit your needs. It seemed like you agreed with Rob conceptually (and I agree with him again).

Now, there are 1000 other improvements to be made to this architecture. The first that comes to mind is to implement a decent caching pattern. For example, you may not want to fetch the comments from the database on each article, every time the article is loaded. So you might want to cache the article and comments and if a comment is added, in your "add comment" code, wipe the article from the cache so it gets rebuild next load. Categories is a perfect example of this... I would typically load something like categories (something that isn't likely to change every 5 minutes) into a master Dictionary (int being the category id) and just reference that in-memory list from my Article code. These are just basic ideas and the concept of caching, relational mapping database or otherwise can get as complicated as you like. I just personally try to adhere to the SubSonic mentality that makes database generation and manipulation so much easier.

Note: If you take a look at the way Linq2SQL does things this approach is very similar at the most basic layer. Linq2SQL typically loads your dependent relationships every time whether you wanted that or knew it was doing it or not. I much prefer the SubSonic "obviousness", if you will, of what is actually happening.

Sorry for the rant but I really hope you can run the above code in a little Console application and get a feel for what I'm getting at.

Dave Jellison
Dave when I did the recommended change, I get a cast exception
Sammy
The same cast exception in the same spot?
Dave Jellison
can not convert fromSystem.Collections.Generic.IEnumarable<System.Linq.IQuerable<IMB.Data.ArticleComment>> toSystem.Collections.Generic.IEnumarable<IMB.Data.ArticleComment>caused by this line list.ForEach(y => y.Comments.AddRange(list.Select(z => z.ArticleComments)));
Sammy
update to list.Select(z => z.ArticleComments).ToList()
Dave Jellison
It sounds as if you may be a little new to some of the Linq extension methods. The one I'm referencing is documented here http://msdn.microsoft.com/en-us/library/bb342261.aspxYou can navigate to some of the basic Linq extension methods from here to familiarize yourself with some of the Linq features you may use often. If you're going to be working with Linq queries you'll want to brush up and use a lot of this stuff. It'll quickly become second nature (and hard to go back to the old way of doing things :)
Dave Jellison
Also, I apologize for the delays in my comments but my email notifications aren't working properly, will try to keep checking back with you.
Dave Jellison
Thanks Dave,You are correct, I haven't done much work with Linq.I did change code back to the way you recommended and still gotten the same build exception. maybe you can answer this question for me.Am I correct to assume Subsonic will return the category object in returned list? I noticed even if I only join with Category table, the Category object is always null.Oarticle.Category is always null regardless of which way I query it.
Sammy
Rewrote my answer
Dave Jellison
Dave,Thank you very much for all your time and effort. I was under the impression that Subsonic behaves the same way as Linq to SQL in terms of relationships. Your last post cleared things up.Once again Thank you very much and Best wishes for the new year.
Sammy
Sammy -I'm very glad I could help and thank you for accepting my answer. I do want to point out, to anyone reading about SubSonic, that just because this is the way that I personally use SS I hope I didn't inadvertently imply that SS is incapable of handling powerful queries and joins. A look at http://subsonicproject.com/docs/Simple_Query_Tool illustrates that SubSonic is indeed capable of these types of queries. I'm personally just saying I won't use it unless I NEED to :) It's a bit like always pulling out the sledgehammer from my toolbox to hang a picture to me :)
Dave Jellison
Dave,I have used subsonic 2.1 and 2.2 in a couple of projects before. It was not the queries I was concerned with, it was the way Subsonic is mapping the relation ships.Articles and Comments would have a one to many relationship. subsonic returned Comments as IQuerable<Comments> instead of IEnumerable.I just need to read up more on linq and checkout subsonic T4 Templates to get used to 3.0.
Sammy
That's cool. I always have trouble finding good documentation for learning new technologies. It seems as soon as things are alpha 0.1 there are 1000 experts with blogs on the subject and I'm left wondering where I was when all this was going on :) For Linq I think I started with http://www.hookedonlinq.com and worked my way up. Obviously, a good book is always handy as well but since I don't have a physical book I can't recommend one ;)
Dave Jellison