简体   繁体   English

SQLite.Net SQLiteException 约束插入

[英]SQLite.Net SQLiteException Constraint insert

I'm using SQLite.Net within a Xamarin Android application.我在 Xamarin Android 应用程序中使用 SQLite.Net。 I have an entity which looks like this:我有一个看起来像这样的实体:

[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; }
}

I have a generic insert method which looks like this:我有一个通用的插入方法,如下所示:

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;
}

I pass the following object into this method:我将以下对象传递给此方法:

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

Occasionally a SQLite exception is thrown with a message of "Constraint", which I understand is a violation of the primary key.有时会抛出 SQLite 异常并显示“约束”消息,我理解这是对主键的违反。

The EntryId column in the (automatically created) table is of type varchar(36). (自动创建的)表中的 EntryId 列是 varchar(36) 类型。

Why would the insert sometimes throw the exception?为什么插入有时会抛出异常?

If I use a non-generic method, that does the insert via a parameterised command, I do not see the exception, but I'd rather use the generic method.如果我使用非通用方法,即通过参数化命令进行插入,我看不到异常,但我宁愿使用通用方法。

In above code 'EntryId' is set as a auto incremented column, So you don't need to insert the 'EntryId' value again and you can set datatype of 'EntryId' is integer.在上面的代码中,'EntryId' 被设置为一个自动递增的列,所以你不需要再次插入 'EntryId' 值,你可以将 'EntryId' 的数据类型设置为整数。

If you want guid type of id, You can set EntryId = Guid.NewGuid().Tostring() in your entity Then every new value inserted in your table automatically create the entryId.(I have not much reputation to comment your question, so I have ping in form of answer.)如果你想要 guid 类型的 id,你可以在你的实体中设置 EntryId = Guid.NewGuid().Tostring() 然后你表中插入的每个新值都会自动创建 entryId。(我没有多少声誉来评论你的问题,所以我有回答形式的ping。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM