C# 在C语言中使用实体框架检索数据库#

C# 在C语言中使用实体框架检索数据库#,c#,entity-framework,lambda,C#,Entity Framework,Lambda,下面我有一段代码,可以很好地工作,但我希望得到其他结果。 此代码显示数据库表中与搜索条件匹配的第一行 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 ||

下面我有一段代码,可以很好地工作,但我希望得到其他结果。 此代码显示数据库表中与搜索条件匹配的第一行

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);
}
但是如果我有多个符合搜索条件的行呢。我想在结果列表中显示所有这些,而不仅仅是第一个符合条件的

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);
}
我试过这个,但出了点问题:

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

我应该如何改进上面的代码来实现这一点?

如果您想获取项目列表,可以在查询结束时使用LINQ.ToList()

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

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

var items = db.userName.Where(x => x.name == txtName.Text || x.City==txtCity.Text).ToList();
使用“var”仅仅意味着系统将通过暗示用法来评估最佳类型。除非你想喊出一个特定的,大多数时候不再需要的

所有这些:

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

if (flag)
{
 // code...
}
完全不需要,因为LINQ的大多数优点是您可以直接内联使用.Where、.Any、.Exists、.Contains等来执行大部分谓词用法。。。然后,您只需使用更多的扩展方法,如:

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

当您执行诸如.First、.Single、.FirstOrDefault等操作时。。。您将您的收藏限制为一次退货。Telist-()或toRayay.()用于实现数据返回到集合返回中更常见。

小注意:<代码> TBL< /Cord>是<代码>用户名,而不是<代码>列表。它起作用了。这就是我想要的。非常感谢你的解释。你的解决方案也有效。我使用if语句检查是否有与搜索条件匹配的记录,如果没有,则显示警告消息。