SQLite-Net Extension both one-to-one and one-to-many relationships between two entities

被刻印的时光 ゝ 提交于 2019-11-30 09:30:23

Yes, but you have to explicitly declare the foreign keys and inverse properties in the relationship attribute, because otherwise the library may get the wrong foreign key for the relationship.

public class ClassA
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [OneToMany("O2MClassAKey", "BObjectsInverse")]
    public List<ClassB> BObjects { get; set; }

    [OneToOne("O2OClassAKey", "BObjectInverse")]
    public ClassB BObject { get; set; }

    // Other properties
    public string Bar { get; set; }
}

public class ClassB
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof (ClassA))]
    public int O2MClassAKey { get; set; }

    [ForeignKey(typeof (ClassA))]
    public int O2OClassAKey { get; set; }

    // Inverse relationships, these are optional
    [ManyToOne("O2MClassAKey", "BObjects")]
    public ClassA BObjectsInverse { get; set; }
    [OneToOne("O2OClassAKey", "BObject")]
    public ClassA BObjectInverse { get; set; }

    // Other properties
    public string Foo { get; set; }
}

Please note that the foreign key O2OClassAKey for the OneToOne relationship can be declared in any of the classes.

If you don't need inverse properties, you can skip them in the relationship attribute:

public class ClassA
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [OneToMany("O2MClassAKey")]
    public List<ClassB> BObjects { get; set; }

    [OneToOne("O2OClassAKey")]
    public ClassB BObject { get; set; }

    // Other properties
    public string Bar { get; set; }
}

public class ClassB
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof (ClassA))]
    public int O2MClassAKey { get; set; }

    [ForeignKey(typeof (ClassA))]
    public int O2OClassAKey { get; set; }

    // Other properties
    public string Foo { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!