0

I have two models, artist and album. And search form, to search artist by its properties, also by its albums. how can I do a join using linq to search artist by its albums? let's assume I have an album name field, and I get in the method artist model as a parameter. This is the code I have, it's search by artist properties now and it's working.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SearchArtist([Bind(Include = "Id,FirstName,LastName,Gender,NickName,Website,Facebook,Twitter,Wikipedia,Background,StartYearActivity,Birthdate")] Artist artist)
    {
        IQueryable<Artist> result = db.Artists;

        if (!String.IsNullOrEmpty(artist.FirstName))
        {
            result = result.Where(x => x.FirstName.Contains(artist.FirstName));
        }

        if (!String.IsNullOrEmpty(artist.LastName))
        {
            result = result.Where(x => x.LastName.Contains(artist.LastName));
        }

        if (!String.IsNullOrEmpty(artist.NickName))
        {
            result = result.Where(x => x.NickName.Contains(artist.NickName));
        }

        if (!String.IsNullOrEmpty(artist.Gender))
        {
            result = result.Where(x => x.Gender.Contains(artist.Gender));
        }

        if (artist.Albums != null && !String.IsNullOrEmpty(artist.Albums.ToList()[0].Name))
        {
// HERE I DON't KNOW HOW TO DO THE JOIN WITH THE NAME OF THE ALBUM
// (ASSUME I HAVE THE NAME OF THE ALBUM TO SEARCH BY IN THE ARTIST PARAMETER)
            result.Where(x => x.Albums.Join()
        }

        List<Artist> finalResult = result.ToList();
        if (finalResult != null && finalResult.Count() > 0)
        {
            return View("Index", finalResult);
        }
        else
        {
            return View("Error");
        }
    }
Uziel Davidi
  • 103
  • 10
  • You can find a lot of information on google. Like [that](http://stackoverflow.com/questions/2767709/c-sharp-joins-where-with-linq-and-lambda) – Xavier W. Oct 19 '15 at 13:20
  • What's the point of doing a join? Isn't is just a matter of filtering the Artist by whether or not the have aan albumm that matches the search string? – Rik Oct 19 '15 at 13:21
  • Yes you right, I can get his albums later. How can I filter the Artist like this? – Uziel Davidi Oct 19 '15 at 13:32
  • Maybe we'll be able to help if you provided details of your `Artist` and `Album` class. – Serhiy Chupryk Oct 19 '15 at 13:43
  • 1
    You dont need a join.. You need to use `Any()` .. but first you need to actually include the album name in your action params.. then just use `result = result.Where(a => a.Albums.Any(b => b.Name == albumname));` – JamieD77 Oct 19 '15 at 13:50
  • works like a charm!! THANKS! – Uziel Davidi Oct 19 '15 at 13:59

0 Answers0