如何解决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' 不包含 'OrderByDescending' 的定义,并且找不到接受类型为 'Task
' 的第一个参数的可访问扩展方法 'OrderByDescending'(您是否缺少 using 指令或程序集参考?)
Product.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);
}
}
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;
}
}
我该如何解决这个问题?谢谢。
解决方法
数据库中的日期时间字段在 .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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。