Alex Rivera | Logout

Linq To Sql Many-Many Join Table

Asked 2009-01-24T21:13:28.267
10

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.

Edit
Report

1 Answer

0

What you can do if you want to create a book and directly want to add a category to it is: in your view:

        <p>
            <label for="CategorySelect">Category:</label>
            <%= Html.ListBox("CategorySelect") %>
            <%= Html.ValidationMessage("CategorySelect", "*")%>
        </p>  

in your bookscontroller:

        public ActionResult New()
    {
            var data = _entities.Categories.ToList();
        ViewData["CategorySelect"] = new MultiSelectList(data, "Id", "Name");
}

        [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult New([Bind(Exclude = "Id")] Book Booknew)
    {
        IEnumerable<int> selectedCategories = Request["CategorySelect"].Split(new Char[] { ',' }).Select(idStr => int.Parse(idStr));

        if (!ModelState.IsValid)
            return View();

        try {
            foreach(var item in selectedCategories){
                BooksCategories bc = new BooksCategories();
                bc.Book = Booknew;
                bc.CategoryId = item;
                _entities.BooksCategories.InsertOnSubmit(bc);
            }
            _entities.Books.InsertOnSubmit(Booknew);
            _entities.SubmitChanges();
answered 2009-05-12T11:01:27.220

Your Answer