Laki
Laki

Reputation: 99

Searching database using Entity Framework in C#

I have a piece of code below which works fine but I want something else to get as the result. This code shows the first row from the database table that matches the searching criteria.

userName tbl = new userName();

bool flag = db.userName.Where(x => x.name == txtName.Text || x.City==txtCity.Text).Any();

if (flag)
{
    tbl = db.userName.Where(x => x.name == txtName.Text || x.City==txtCity.Text).First();
    userNameBindingSource.DataSource = tbl;
}
else
{
    MessageBox.Show("This record does not exist in the database.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

But what if I have multiple rows that match the searching criteria. I want to show all of them in the result list, not just the first one which matches the criteria.

I have tried this, but something went wrong:

tbl = db.userName.Where(x => x.name == txtName.Text || x.City==txtCity.Text).All();

How should I refine the code above to achieve this?

Upvotes: 3

Views: 8805

Answers (2)

djangojazz
djangojazz

Reputation: 13272

Change this:

tbl = db.userName.Where(x => x.name == txtName.Text || x.City==txtCity.Text).First();

to this:

var items = db.userName.Where(x => x.name == txtName.Text || x.City==txtCity.Text).ToList();

Using the 'var' just means the system will evaluate the best type by implying usage. Unless you want to call out a specific, which most times is no longer needed.

All of this:

bool flag = db.userName.Where(x => x.name == txtName.Text || x.City==txtCity.Text).Any();

if (flag)
{
 // code...
}

is completely unneeded as most things that are nice about LINQ is you can do most of the predicate usage directly inline with .Where, .Any, .Exists, .Contains, etc... Then you merely chain off of that with more extension methods something like:

context.(tableOrObject)
  .Where(x => x.Prop == (somePredicate))
  .Select(x => new { Id = x.Id, Desc = (some series of things)})
  .ToList();

When you do something like.First, .Single, .FirstOrDefault, etc... you are limiting your collection to a single return. .ToList() or .ToArray() are more common for realizing your data into a collection return.

Upvotes: 3

Chrissx
Chrissx

Reputation: 357

If you want to get back a List of items you can use LINQ .ToList() on end of your query.

List<UserName> tbl = db.UserNames.Where(x => x.Name == txtName.Text || x.City == txtCity.Text).ToList();

This will evaluate your IQueryable that you build with DBContext. ToList will return a list of your entities. You can use ToArray also :)

.All() is for validating all your item in your enumeration match with your expression. Example:

.All(x=> x.Contains("text")).

Upvotes: 4

Related Questions