简体   繁体   中英

SQLite.Net SQLiteException Constraint insert

I'm using SQLite.Net within a Xamarin Android application. 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.

The EntryId column in the (automatically created) table is of type 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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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