首页 > 解决方案 > SQLite 和 LINQ:“成员访问无法编译表达式”(WHERE 条件)

问题描述

我有一个带有 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: '成员访问编译表达式失败'

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

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

return item.ToListAsync();

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

错误 CS1061 'Task<List>' 不包含 'OrderByDescending' 的定义,并且找不到接受“Task<List>”类型的第一个参数的可访问扩展方法 'OrderByDescending'(您是否缺少 using 指令或程序集参考?)

产品.cs:

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

数据库.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);
     }
}

应用程序.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;
            }
}

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

标签: c#sqlitelinqlinq-to-sql

解决方案


数据库中的 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)

推荐阅读