在 Visual Studio 中使用带有 Marten 的 Linq 查询多个参数

Querying multiple parameters using Linq with Marten in Visual Studio

我正在学习文档数据库,我们正在 Visual Studio 中使用 Marten/Linq。数据库是 运行 到 Postgres/PGAdmin。我的数据库是足球(不是美国)联赛、球队、球员和经理。我正在尝试基于多个参数构建查询。我的奇异参数很好。

List<Player> englishPlayers = finalDb.Query<Player>().Where(x => x.Nationality.Contains("English")).ToList();

此查询将创建一个列表,其中包含文档数据库中国籍设置为 "English" 的所有玩家。

玩家是我的class/table,国籍"field"。我想做的是基于多个参数的查询。例如,我有多个 "fields" 是 int 或 bool。例如,如果我想创建一个查询来显示 lifetimeGoals > 100 的特定国籍的所有玩家,我将如何实现?

我搜索了 Google 大约一个小时,并通读了建议的类似问题,但其中大部分问题都没有说明使用了 Marten。

我试过先按单个查询将其分解,然后再组合它们,例如:

Player m4 = finalDb.Query<Player>().SelectMany(e => e.lifetimeGoals
                .Where(p => e.lifetimeGoals >= 0));

但是,这会引发错误

int does not contain a definition for where, and no extension method 'Where' accepting a first argument of type 'int'.

我的术语有点偏离,但希望这足够清楚以找到指导。

Class 玩家:

class Player
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Team { get; set; }
    public string prefPosition { get; set; }
    public string Nationality { get; set; }
    public int yearsAtCurrentClub { get; set; }
    public int lifetimeGoals { get; set; }
    public int domesticTitles { get; set; }
    public int europeanTitles { get; set; }
}//Class Player

主要class

static void Main(string[] args)
    {

        string connectionString = ConfigurationManager.ConnectionStrings
        ["FinalProjectDB"].ConnectionString;
        IDocumentStore store = DocumentStore.For(connectionString);

        using (var finalDb = store.OpenSession())
        {
        Player m4 = finalDb.Query<Player>().SelectMany(p => p.lifetimeGoals)
                    .Where(p => p.lifetimeGoals >= 0 && p.myString.Equals("valueToCheck"));

 Console.ReadLine();
 }

您不能对整数使用 .Where()。而是像这样使用它:

Player m4 = finalDb.Query<Player>().SelectMany(e => e.lifetimeGoals)
            .Where(p => p.lifetimeGoals >= 0);

上述查询在 SelectMany 末尾有一个右括号,允许 Where 子句与预期查询一起使用。

由于在 SelectMany 的末尾添加了一个括号,因此无需在查询末尾添加一个额外的括号。

编辑: 您只需在 .Where()

中添加另一个子句
Player m4 = finalDb.Query<Player>().SelectMany(e => e.lifetimeGoals)
            .Where(p => p.lifetimeGoals >= 0 && p.myString.Equals("valueToCheck"));

您可以将 && 用于 或者您可以将 || 用于 .

第二次编辑: 我不明白你为什么要使用 .SelectMany()。您应该能够像这样使用您的查询:

Player m4 = finalDb.Query<Player>().Where(p => p.lifetimeGoals >= 0 && p.myString.Equals("valueToCheck")).FirstOrDefault();

或者当你想要玩家列表时使用.ToList()

List<Player> players = finalDb.Query<Player>().Where(p => p.lifetimeGoals >= 0 && p.myString.Equals("valueToCheck")).ToList();