繁体   English   中英

使用 LINQ 和 EF Core 查询

[英]Querying with LINQ and EF Core

我正在执行一项任务,该任务要求我搜索数据库以返回用户输入的城市中的公司名称。

我创建的方法可以正常工作并完成预期的工作,但是有两个问题:

  1. 它在第一个foreach语句中打印了 6 次而不是仅一次。
  2. 它没有在第一个foreach语句中返回正确数量的客户。

这是完整的方法:

static void ReturnCities()
{
    WriteLine("Enter the name of a city: ");
    string? city = ReadLine();

    using (var db = new Northwind())
    {
        // query to find all customers in the
        // city that was entered
        var query = db.Customers
                      .Where(customer => customer.City == city)
                      .Select(customer => new
                              {
                                  customer.City
                              });

        // prints a statement with how many customers
        // are in the city entered
        foreach (var item in query)
        {
            WriteLine("There are {0} customers in {1}: ",
                      arg0: item.City.Count(),
                      arg1: item.City);
        }

        // query to return a list of all customers 
        // in the city entered       
        var query2 = db.Customers
                       .Where(customer => customer.City == city)
                       .Select(customer => new
                               {
                                   customer.CompanyName
                               });

        foreach (var item2 in query2)
        {
            WriteLine($"    {item2.CompanyName} ");
        }
    }
}

output 目前是:

Enter the name of a city: 
London
There are 6 customers in London: 
There are 6 customers in London: 
There are 6 customers in London:
There are 6 customers in London:
There are 6 customers in London:
There are 6 customers in London:
    Around the Horn
    B's Beverages
    Consolidated Holdings
    Eastern Connection
    North/South
    Seven Seas Imports

我不确定是什么导致了除foreach语句之外的第一个问题,可能是因为它为查询中的每个项目返回了一个打印语句,但我无法修复它。

我目前仍在尝试解决第二个问题,但是对于这两个问题的任何和所有提示都表示赞赏!

您的查询将只返回Your query will just return an IQueryable<string> { "london", "london", "london" }因为Select()

您可以简单地对您的代码进行 1 次查询...

var query = db.Customers
    .Where(customer => new() {
        customer.City,
        customer.CompanyName
    });

var count = query.Count();
// output: 6

foreach(var customer in query) 
{
    Console.Writeline(customer.CompanyName);
}

// output:
//    Around the Horn
//    B's Beverages
//    Consolidated Holdings
//    Eastern Connection
//    North/South
//    Seven Seas Imports

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM