c# - 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;
}
}
我该如何解决这个问题?谢谢你。
解决方案
数据库中的 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)
推荐阅读
- reactjs - 赛普拉斯没有检测来自 cy.route() 的路由
- javascript - 在 plotly 模板中添加多个 csv 文件
- reactjs - 如何显示蚂蚁设计时间选择器未来时间
- javascript - 如何将数组复制到功能状态?
- css - Quasar 表根据一个单元格中的值更改整行的样式
- flutter - Flutter 共享首选项与原生共享首选项
- javascript - 如何在特定位置存储或上传音频文件?
- android - 如何为同一个 xml 属性使用 2 个不同的值.....有可能吗?
- python - python:int子类的子类
- swift - 从 WKWebView 保存 PDF