Search code examples
sqlitexamarin.formssqlite-net-extensions

SQLiteNetExtensions multiple ManyToOne relations of same type


I'm trying xamarin app... and I needed sqlite database... that contain 3 tables... users, accounts and transactions... the table of account seems:

[Table(nameof(Account))]
class Account
{
    [PrimaryKey,AutoIncrement]
    public int Id { get; set; }

    public string Name { get; set; }

    [ForeignKey(typeof(User))]
    public int UserId { get; set; }

    public double Balance { get; set; }

    [ManyToOne]
    public User User { get; set; }

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

I think there is no problem until here... but in transaction table there are tow columns, FirstAccountId and TargetAccountId,so I like that:

[Table(nameof(Transaction))]
class Transaction
{
    [PrimaryKey,AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof(Account))]
    public int TargetAccountId { set; get; }

    [ForeignKey(typeof(Account))]
    public int FirstAccountId { get; set; }

    public DateTime DateOfTransaction { get; set; }

    [ManyToOne()]
    public Account Account1 { get; set; }

    [ManyToOne()]
    public Account Account2 { get; set; }`
}

How I can make Account1 is the account for FirstAccountId and Account2 is the account for TargetAccountId


Solution

  • According to the source code of ManyToOne (see here), it takes an string foreignKey as a parameter. I did not find anything about it in the documentation, but I'd assume that you can specify an foreign key explicitly using this parameter, although I did not find anything about it in the documentation

    [ManyToOne(nameof(FirstAccountId))]
    public Account Account1 { get; set; }
    
    [ManyToOne(nameof(TargetAccountId))]
    public Account Account2 { get; set; }