获取错误:日期比较时出现System.NotSupportedException

时间:2017-07-31 18:49:00

标签: sqlite xamarin xamarin.android xamarin.forms android-sqlite

所以我试图在UserDatabse.cs类中使用此方法检索特定日期的类“Sugar”的实例:

public List<Sugar> GetSugarDate(DateTime dt)  
        {  
              var bld = database.Table<Sugar>().Where(mi => mi.Time.Date == dt.Date).ToList();  
            return bld;  
        }  

*请记住,该应用目前没有Sugar的任何实例,所以Date比较介于null和实际日期之间。我认为这会导致错误,任何解决方案都会受到赞赏。

在另一个类中调用此方法:

            DateTime Time = DateTime.Now;

            ObservableCollection<Image> Sugar_Count = new ObservableCollection<Image>();
            Image s = new Image();
            s.Source = "drawable/soda.png";
            var xa = App.Database.GetSugarDate(Time);

Sugar.cs类定义如下:

 public class Sugar
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public DateTime Time { get; set; }
        public int DrinkCount { get; set; }

        public Sugar()
        {
            Time = DateTime.Now;
            DrinkCount = 0;
        }
}  

现在错误是获得如下:

System.NotSupportedException: Member access failed to compile expression at SQLite.TableQuery'1[T].CompileExpr(System.Linq.Expressions.Expression expr, System.Collections.Generic.List'1[T]queryArgs)[0x006cc]in <9b4aaa861238418bec74a2ddde70f09>:0 at SQLite.TableQuery'1[T].CompileExpr(System.Linq.Expressions.Expression expr, System.Collections.Generic.List'1[T]queryArgs)[0x0009d]in <9b4aaa861238418bec74a2ddde70f09>:0 at SQLite.TableQuery'1[T].CompileExpr(System.Linq.Expressions.Expression expr, System.Collections.Generic.List'1[T]queryArgs)[0x0005f]in <9b4aaa861238418bec74a2ddde70f09>:0 at SQLite.TableQuery'1[T].CompileExpr(System.Linq.Expressions.Expression expr, System.Collections.Generic.List'1[T]queryArgs)[0x00008]in <9b4aaa861238418bec74a2ddde70f09>:0 at
System.Collections.Generic.List'1[T]..ctor(System.Collections.Generic.IEnumerable'1[T]collection)[0x00062] in /Users/builder/jenkins/workspace/xamarin-android/external/mono/mcs/class/referencesource/generic/list.cs:98 .....

错误发生在以下特定行:

var bld = database.Table<Sugar>().Where(mi => mi.Time.Date == dt.Date).ToList();

我哪里错了?

2 个答案:

答案 0 :(得分:1)

这部分表达式无法转换为SQL。

mi => mi.Time.Date

您可以尝试使用:

var bld = database.Table<Sugar>().ToList().Where(mi => mi.Time.Date == dt.Date).ToList();
  

访问DateTime列的日期部分(mi.Time.Date)无法使用Linq转换为SQL,因此,您的语句最初失败。因此,使用ToList获取内存中的所有记录,允许我们使用 Linq to Object 方法进行查询,而不是 Linq to SQLite

答案 1 :(得分:0)

有点笨拙,但我可以使用它:

public List<Sugar> GetSugarDate(DateTime dt)
{
    var dayStart = dt.Date.AddDays(-1);
    var dayEnd = dt.Date.AddDays(1);

    var bld = database.Table<Sugar>().Where(mi => mi.Time > dayStart && mi.Time < dayEnd).ToList();
    return bld;
}

还要确保您使用以下方法初始化数据库连接:

SQLiteConnection database = new SQLiteConnection(_path,false);

如果要查询可为空的DateTime