【问题标题】:SQLite and LINQ: 'Member access failed to compile expression' (WHERE Condition)SQLite 和 LINQ:“成员访问无法编译表达式”(WHERE 条件)
【发布时间】:2021-05-01 20:36:55
【问题描述】:

我有一个带有 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 指令还是程序集参考?)

产品.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;
            }
}

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

【问题讨论】:

  • 您的 LINQ 提供程序未解析 DateTime.Today 可能将其存储在变量中并在 OrderBy 中使用它。不要这样做ToList,它会将整个表从数据库中取出

标签: c# sqlite linq linq-to-sql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-02
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多