Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq To Sql Many-Many Join Table

I am a somewhat experienced Rails developer and I thought I would try out ASP.NET's version of MVC. In doing so I also decided to try Linq->Sql...

I am a bit confused about the way Linq->Sql handles joins.

A trivial example of my schema is :

books:
id
title

categories:
id
name

books_categories:
book_id
category_id

Simply dragging these tables to the .dbml file doesn't seem to do it. I get a property on my Book class books_categories, what I expect is a property that I can iterate over and get Category classes directly.

Right now I have to do something that feels very wrong

        foreach (books_categories bc in book.books_categories)
        {
            category_names.Add(bc.Category.category.Trim());
        }

[In Response to Accepted answer]
I grudgingly accepted the answer of "write your own glue code". After continuing my research of Linq->Sql I discovered that it is apparently slowly being let go in favor of the (more powereful, IMO) Entity Framework. EF still allows one to use LINQ for queries and does a decent job of figuring out relationships like Ruby's ActiveRecord.

like image 696
Bill Avatar asked Jan 24 '09 21:01

Bill


1 Answers

Use a partial class implementation for Book and add appropriate methods for categories and their properties. Have the properties front-end the Books_Categories property (you can make this have private visibility to force implementation through your Categories property).

public partial class Books
{
    public IEnumerable<string> CategoryNames
    {
       get
       {  
            return this.Books_Categories
                       .Select( bc => bc.Category.category.Trim() );
       }
    }

    public void AddCategory( Category category )
    {
       this.Books_Categories.Add( new Book_Category
                                  {
                                      Category = category,
                                      Book = this
                                  } );
    }

    public void RemoveCategory( Category category )
    {
       var bc = this.Book_Categories
                    .Where( c => c.Category == category )
                    .SingleOrDefault();
       this.Books_Categories.Remove( bc );
    }
}

Obviously, you'll need to add some error/bounds checking, etc. but you get the idea.

I'll grant you this is not ideal, but at least you have the flexibility to determine how it works.

like image 121
tvanfosson Avatar answered Sep 18 '22 20:09

tvanfosson