【发布时间】: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