【问题标题】:SQLite.Net SQLiteException Constraint insertSQLite.Net SQLiteException 约束插入
【发布时间】:2017-06-09 06:50:23
【问题描述】:

我在 Xamarin Android 应用程序中使用 SQLite.Net。我有一个看起来像这样的实体:

[DataEntity]
public class AuditEntity
{
        [PrimaryKey]
        public Guid EntryId { get; set; }

        public string Action { get; set; }        
        public string GeoLocation { get; set; }        
        public DateTime Time { get; set; }
}

我有一个通用的插入方法,如下所示:

public int Insert<T>(T obj) where T : class
    {
                var result = 0;

                try
                {                
                    result = Connection.Insert(obj);                
                }
                catch (SQLiteException ex)
                {               
                    Mvx.Trace(MvxTraceLevel.Error, $"Exception while inserting into database:\r\n{ex.ToLongString()}");
                }

                return result;
}

我将以下对象传递给此方法:

var auditEntry = new AuditEntity
{
                EntryId = Guid.NewGuid(),
                Action = uri.ToString(),
                GeoLocation = geoLocation,
                Time = DateTime.Now
};

偶尔会抛出 SQLite 异常并显示“约束”消息,据我所知这是违反主键。

(自动创建的)表中的 EntryId 列的类型为 varchar(36)。

为什么插入有时会抛出异常?

如果我使用非泛型方法,即通过参数化命令进行插入,我看不到异常,但我宁愿使用泛型方法。

【问题讨论】:

  • 您使用的是哪个 sql.net dll?我已经在 xamarin android 中尝试过SQLite Component。没有找到Connection.insert(obj) 方法。
  • 您有其他具有相似属性的实体类型吗?如果是这样,连接可能会误认为要插入哪个表。
  • 感谢您的提示。我们有其他实体使用 Guid 作为主键,但具有不同的属性名称,例如“日志ID”。有些还具有“时间”属性。我看到 Insert 方法的重载采用“类型”参数。我将使用该重载,看看它是否有所作为。
  • 使用重载没有帮助。

标签: c# android xamarin sqlite.net


【解决方案1】:

在上面的代码中'EntryId'被设置为一个自动递增的列,所以你不需要再次插入'EntryId'值,你可以设置'EntryId'的数据类型是整数。

如果您想要 id 的 guid 类型,您可以在您的实体中设置 EntryId = Guid.NewGuid().Tostring() 然后插入表中的每个新值都会自动创建 entryId。(我没有太多声誉可以评论您的问题,所以我以答案的形式ping。)

【讨论】:

  • 你的答案不正确。如果我没有在要插入的对象上指定 ID,则该值存储在数据库中的未初始化 Guid 中。我也不想将 ID 的类型从 Guid 更改为字符串; Guid 是正确的类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多