Thursday, May 26, 2011

JOIN two tables using LINQ to SQL

// GET: /Store/Browse?genre=Disco

public ActionResult Browse(string genre)
{
//var genreModel = new Genre { Name = genre };
//var albums = from m in storeDB.Albums
// where m.Genre.Name == genre
// select m;

var albums = from m in storeDB.Albums
join v in storeDB.Genres
on m.GenreId equals v.GenreId
where v.Name == genre
select m;

var albumList = albums.ToList<Album>();

return View(albumList);

}

///Acess this list at View of MVC Application
@model IEnumerable< MvcMusicStore.Album>
@{
ViewBag.Title =
"Browse";
}

<h2>Browsing Genre: @Model.Count()</h2>
<
ul>
@foreach (var album in Model)
{

//<li><a href="/Store/Browse?genre=@genre.Name">@genre.Name</a></li>
//<li>@Html.ActionLink(genre.Name,"Browse",new {genre=genre.Name})</li>
<li>@album.Title</li>
}
</ul>

 

No comments :

Post a Comment