gpt4 book ai didi

c# - sqlite net extensions InsertOrReplaceWithChildren 不插入子外键字段

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:26 25 4
gpt4 key购买 nike

我有以下类(class):

class A
{
[PrimaryKey]
public int A_ID { get; set; }

[OneToMany(CascadeOperations=CascadeOperation.All)]
public List<B> Children { get; set; }
}

class B
{
[PrimaryKey]
public int B_ID { get; set; }

[ForeignKey(typeof(C))]
public int C_ID { get; set; }
}

class C
{
[PrimaryKey]
public int C_ID { get; set; }
}

当我有一个 A 的实例和 B 的子实例时,执行 db.InsertOrReplaceWithChildren(aInstance, recursive: true);确实会导致 A 及其子 B 被插入到数据库中,但是每个外键值 B.C_ID 始终默认为 0,尽管它们有一个值。

例子:

A aInstance = new A();
aInstance.A_ID = 1;

B bInstance = new B();
bInstance.B_ID = 1;

C cInstance = new C();
cInstance.C_ID = 1;

bInstance.C_ID = cInstance.C_ID; //assigning the many-to-one foreign key of B to C
aInstance.Children.Add(bInstance); //assigning the one-to-many child record of A to B

//do the insert
db.InsertOrReplaceWithChildren(aInstance, recursive:true);

当我选择记录B时:

B bDatabaseRecord = db.Get<B>(bRecord => bRecord.B_ID == bInstance.B_ID).First();
//bDatabaseRecord.C_ID is 0 <-- the problem

最佳答案

我遇到了这个问题,它通过在类 B 中识别类 C 的对象(作为外键对象)并将关系标记为 ReadOnly=true 来解决。所以代码应该是

class A
{
[PrimaryKey]
public int A_ID { get; set; }

[OneToMany(CascadeOperations=CascadeOperation.All)]
public List<B> Children { get; set; }
}

class B
{
[PrimaryKey]
public int B_ID { get; set; }

[OneToOne(ReadOnly=true)]
public C C_Obj { get; set; }

[ForeignKey(typeof(C))]
public int C_ID { get; set; }
}

class C
{
[PrimaryKey]
public int C_ID { get; set; }
}

我希望这个解决方案对你有用:)

关于c# - sqlite net extensions InsertOrReplaceWithChildren 不插入子外键字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42234990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com