【问题标题】:Get most recent datetime column with LINQ使用 LINQ 获取最新的日期时间列
【发布时间】:2019-01-04 19:21:36
【问题描述】:

我有一个反映 SQLite 表的简单类。

class SyncAudit
{
    public string Server { get; set; }
    public string Database { get; set; }
    public string SyncTime { get; set; }
    public int Successful { get; set; }
}

我正在尝试构造一个返回最近同步时间的 LINQ 方法。

    public string getLastSyncTime()
    {
        using (var db = new SQLite.SQLiteConnection(this.DBPath))
        {
            var query = db.Table<SyncAudit>()
                .OrderByDescending(c => c.SyncTime)
                .Select(c => c.SyncTime)
                .FirstOrDefault();
            return query.ToString();
        }
    }

我正在尝试在 SQLite 数据库中查找最近的同步时间并将其作为字符串返回。

我做错了什么?

编辑:我收到以下错误:

An exception of type 'System.MissingMethodException' occurred in mscorlib.dll but was not handled in user code

Additional information: No parameterless constructor defined for this object.

使用:https://components.xamarin.com/view/sqlite-net

【问题讨论】:

  • 这看起来不错,有什么问题? SyncTime 真的是数据库中的string,还是应该是DateTime
  • 您没有得到MissingMethodException 显示的代码。
  • 这是我遇到的错误。但是,将模型更改为 DateTime 可以解决此问题。

标签: c# linq


【解决方案1】:

SyncTime 是模型中的一个字符串,但似乎是(或应该是)DateTime。所以在数据库中修复它。如果这是不可能的,你必须解析它:

DateTime lastSyncTime = db.Table<SyncAudit>().AsEnumerable() // Do the rest of the processing in memory
    .Select(c => DateTime.Parse(c.SyncTime))
    .OrderByDescending(dt => dt)
    .FirstOrDefault();
return lastSyncTime;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-26
    • 2016-10-02
    • 1970-01-01
    • 2016-11-09
    • 2021-04-16
    • 2011-09-06
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多