0

I have a Person model in ASP.NET MVC, and I'm working with DbContext, and I have a DbSet to this model. I have first name, last name, nick name fields. I want to know how can I select persons with DbSet with several conditions.

If it was SQL, I want to do this:

select * from persons where firstName like '%something%' and
lastName like '%something%' and
nickName like '%something%';

How can I do it with DbSet? I have the next code:

    public ActionResult SearchPerson([Bind(Include = "Id,FirstName,LastName,NickName")] Person person)
    {
        DbSet<Person> result = db.Persons;
        if (!String.IsNullOrEmpty(person.FirstName))
        {
            result.Where(x => x.FirstName.Contains(person.FirstName));
        }

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

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

        return View(result.ToList());
    }

It seems the is no AND clause or any WHERE clause between the conditions, and result.ToList() gives me ALL the results from the DB. Any help?

tereško
  • 58,060
  • 25
  • 98
  • 150
Uziel Davidi
  • 103
  • 10

0 Answers0