code_junkie

Linq To Sql Many-Many Join Table

Nov 13th, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. foreach (books_categories bc in book.books_categories)
  2. {
  3. category_names.Add(bc.Category.category.Trim());
  4. }
  5.  
  6. public partial class Books
  7. {
  8. public IEnumerable<string> CategoryNames
  9. {
  10. get
  11. {
  12. return this.Books_Categories
  13. .Select( bc => bc.Category.category.Trim() );
  14. }
  15. }
  16.  
  17. public void AddCategory( Category category )
  18. {
  19. this.Books_Categories.Add( new Book_Category
  20. {
  21. Category = category,
  22. Book = this
  23. } );
  24. }
  25.  
  26. public void RemoveCategory( Category category )
  27. {
  28. var bc = this.Book_Categories
  29. .Where( c => c.Category == category )
  30. .SingleOrDefault();
  31. this.Books_Categories.Remove( bc );
  32. }
  33. }
  34.  
  35. <p>
  36. <label for="CategorySelect">Category:</label>
  37. <%= Html.ListBox("CategorySelect") %>
  38. <%= Html.ValidationMessage("CategorySelect", "*")%>
  39. </p>
  40.  
  41. public ActionResult New()
  42. {
  43. var data = _entities.Categories.ToList();
  44. ViewData["CategorySelect"] = new MultiSelectList(data, "Id", "Name");
  45. }
  46.  
  47. [AcceptVerbs(HttpVerbs.Post)]
  48. public ActionResult New([Bind(Exclude = "Id")] Book Booknew)
  49. {
  50. IEnumerable<int> selectedCategories = Request["CategorySelect"].Split(new Char[] { ',' }).Select(idStr => int.Parse(idStr));
  51.  
  52. if (!ModelState.IsValid)
  53. return View();
  54.  
  55. try {
  56. foreach(var item in selectedCategories){
  57. BooksCategories bc = new BooksCategories();
  58. bc.Book = Booknew;
  59. bc.CategoryId = item;
  60. _entities.BooksCategories.InsertOnSubmit(bc);
  61. }
  62. _entities.Books.InsertOnSubmit(Booknew);
  63. _entities.SubmitChanges();
Add Comment
Please, Sign In to add comment