嗨,我正在尝试测试是否删除父对象,使用 OrmLite 和内存数据库 Sqlite 也会自动删除子对象
这是我的测试代码,但它向我抛出 System.Data.SQLite.SQLiteExceptionSQL 逻辑错误或“)”附近缺少数据库:db.Save() 行的语法错误。
可能出了什么问题?
[Fact]
public void DeleteById_AlsoDeleteChild_Test()
{
var _dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
using (var db = _dbFactory.OpenDbConnection())
{
// arrange
db.CreateTableIfNotExists<Foo>();
db.CreateTableIfNotExists<Bar>();
var foo = new Foo
{
Bar = new Bar
{
Name = "Hello"
}
};
db.Save(foo);
db.SaveReferences(foo, foo.Bar);
var saved = db.Select<Foo>();
// act
db.DeleteById<Foo>(saved.First().Id);
// assert
Assert.False(db.Exists<Bar>(c => c.FooId == saved.First().Id));
}
}
public class Foo : IHasIntId
{
[AutoIncrement]
public int Id { get; set; }
[Reference]
public Bar Bar { get; set; }
}
public class Bar : IHasIntId
{
[AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Foo), OnDelete = "CASCADE")]
public int FooId { get; set; }
public string Name { get; set; }
}
System.Data.SQLite.SQLiteExceptionSQL逻辑错误或缺少数据库
“)”附近:语法错误 在 System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn、String strSql、SQLiteStatement previous、UInt32 timeoutMS、ref String strRemain) 在 System.Data.SQLite.SQLiteCommand.BuildNextCommand() 在 System.Data.SQLite.SQLiteDataReader.NextResult() 在 System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd、CommandBehavior 行为) 在 System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior 行为) 在 System.Data.SQLite.SQLiteCommand.ExecuteScalar(CommandBehavior 行为) 在 ServiceStack.OrmLite.OrmLiteReadCommandExtensions.LongScalar(IDbCommand dbCmd) 在 ServiceStack.OrmLite.OrmLiteWriteCommandExtensions.Save(IDbCommand dbCmd,T obj) 在 ServiceStack.OrmLite.OrmLiteWriteApi.<>c__DisplayClass39' 1. b__38(IDbCommand dbCmd) 在 ServiceStack.OrmLite.OrmLiteExecFilter.Exec(IDbConnection dbConn,Func`2 过滤器) 在 Class1.cs 中的 ClassLibrary2.Class1.DeleteById_AlsoDeleteChild_Test() 处:第 35 行
最佳答案
此问题是因为 Foo
没有任何要 INSERT 的列,因为 Id
是自动递增主键,而 Bar
是 [Reference]
属性,因此不会保存任何列,因此 INSERT SQL 最终看起来像:
INSERT INTO "Foo" () VALUES ();
如果您 Foo
有一个列,那么这将起作用,例如:
public class Foo : IHasIntId
{
[AutoIncrement]
public int Id { get; set; }
[Reference]
public Bar Bar { get; set; }
public string Name { get; set; }
}
注意默认情况下,SQLite 中不启用外键支持。每次使用编译指示连接到数据库时,您都需要手动启用它:
PRAGMA foreign_keys = ON
因此,一个有效的示例如下所示:
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<Foo>();
db.DropAndCreateTable<Bar>();
db.ExecuteNonQuery("PRAGMA foreign_keys = ON");
var foo = new Foo
{
Bar = new Bar
{
Name = "Hello"
}
};
db.Save(foo);
db.SaveReferences(foo, foo.Bar);
var saved = db.Select<Foo>();
db.DeleteById<Foo>(saved.First().Id);
Assert.False(db.Exists<Bar>(c => c.FooId == saved.First().Id));
}
关于c# - OrmLite : SQLiteExceptionSQL logic error or missing database near ")": syntax error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30319075/