【问题标题】:sqlite net extensions InsertOrReplaceWithChildren not inserting children foreign key fieldssqlite net extensions InsertOrReplaceWithChildren 不插入子外键字段
【发布时间】:2017-07-03 06:20:57
【问题描述】:

我有以下课程:

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

【问题讨论】:

    标签: c# sqlite xamarin sqlite-net


    【解决方案1】:

    我遇到了这个问题,通过在 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; }
    } 
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2017-02-15
      • 2015-12-11
      相关资源
      最近更新 更多