SQLite 和 LINQ:'Member access failed to compile expression'(WHERE 条件)

SQLite and LINQ: 'Member access failed to compile expression' (WHERE Condition)

我有一个带有 ListView 的 Xamarin.Forms 页面,该页面在出现时应该填充 5 个最近的产品日期,其中日期是今天的日期。我正在使用 SQLite 数据库来存储新产品进入库存的日期和时间。

我在 Database.cs 中遇到此查询问题:

return _database.Table<Product>().OrderByDescending(x => x.ProductDateTime)
       .Where(y => y.ProductDateTime.Date == DateTime.Today).Take(5).ToListAsync();

这部分查询导致错误:

Where(y => y.ProductDateTime.Date == DateTime.Today)

System.NotSupportedException: 'Member access failed to compile expression'

我试图通过尝试使用 ToList() / ToListAsync() 来解决这个问题。

var item = _database.Table<Product>().ToListAsync().OrderByDescending(x => x.ProductDateTime).Where(y => y.ProductDateTime.Date == DateTime.Today).Take(5);

return item.ToListAsync();

但是,这会导致不同的错误:

Error CS1061 'Task<List>' does not contain a definition for 'OrderByDescending' and no accessible extension method 'OrderByDescending' accepting a first argument of type 'Task<List>' could be found (are you missing a using directive or an assembly reference?)

Product.cs:

public class Product
{ 
     [PrimaryKey, AutoIncrement]
     public int ID { get; set; }
     public DateTime ProductDateTime { get; set; }
}

Database.cs:

public class Database
{
     readonly SQLiteAsyncConnection _database;

     public Database(string dbPath)
     {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<Product>().Wait();
     }

     public Task<List<Product>> GetProductAsync()
     {

          return _database.Table<Product>().OrderByDescending(x => x.ProductDateTime).Where(y => y.ProductDateTime.Date == DateTime.Today).Take(5).ToListAsync();

     }

     public Task<int> SaveProductAsync(Product product)
     {
            return _database.InsertAsync(product);
     }
}

App.xaml.cs:

static Database database;

public static Database Database
{
            get
            {
                if (database == null)
                {
                    database = new Database(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "product.db3"));
                }
                return database;
            }
}

我该如何解决这个问题?谢谢。

数据库中的 DateTime 字段在 .NET 中没有 DateTime.Date 属性 的等效项。 我会尝试这样的事情:

var yesterday = DateTime.Today.AddDays(-1);
var tomorrow = DateTime.Today.AddDays(1); // <-- omit this, if your database doesn't have any rows with ProductDateTime in the future
....
Where(y => y.ProductDateTime > yesterday &&  y.ProductDateTime < tomorrow)