我正在使用 SQLite-Net PCL 和 SQLite-Net 扩展来开发使用 Xamarin 的应用程序。
在我的模型中,我有一个实体(我们称之为 A),它通过一对多关系(在模型中表示为列表)连接到其他四个实体。为了在数据库中插入 A 的对象时递归地填充表,我定义了在读取、插入和删除时使用 Cascade 的关系。
为了测试我是否正确执行了所有操作,我创建了一个 A 类型的对象并填充了包含列表,最后我将它插入到数据库中。奇怪的是,对于 4 个包括列表中的 2 个,插入进行得很顺利,并且所有连接的对象都被插入。相反,对于其他 2,只有列表的第一个对象被插入到数据库中。需要明确的是,我正在使用 db 浏览器直接检查数据库内容。
以下是仅插入列表的第一个元素的对象之一的示例。
public class Username : Entity
{
public string Name
{
get;
set;
}
[ForeignKey(typeof(A))]
public int AId
{
get;
set;
}
public Username(string username)
{
Name = username;
}
}
相反,这是插入正确的对象之一。
public class AnAddress: Entity
{
public string Address
{
get;
set;
}
public AddressType Type
{
get;
set;
}
[ForeignKey(typeof(A))]
public int AId
{
get;
set;
}
}
需要明确的是,基础对象 Entity 包含主键的定义:
public abstract class Entity
{
[PrimaryKey, AutoIncrement]
public int Id
{
get;
set;
}
public Entity()
{
Id = -1;
}
}
这就是定义关系的方式:
public class A : Entity
{
public string Name
{
get;
set;
}
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<AnAddress> Addresses
{
get;
set;
}
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<Username> Usernames
{
get;
set;
}
}
然后,我通过以相同方式使用两个列表(List 和 List)对其进行初始化来创建 A 对象。我终于将对象插入到数据库中
c.InsertWithChildren(entity, recursive: true));
其中 entity 是 A 类型,而 c 是连接对象。
你对这种奇怪行为的动机有任何线索吗?