How to specify a foreign key property in SQLite-Net Extensions

Alexei Vinidiktov picture Alexei Vinidiktov · Aug 22, 2015 · Viewed 8.6k times · Source

How do I specify a foreign key that references a specific property instead of the primary key?

For example the Stock class has a uuid property. And I want to create a foreign key in the Valuation class that references it using this property.

In the following example the line [ForeignKey(typeof(Stock))] references the ID property of the Stock class, but I need it to reference the UUID property.

How would I do that?

public class Stock
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string UUID { get; set; } 
    [MaxLength(8)]
    public string Symbol { get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]      // One to many relationship with Valuation
    public List<Valuation> Valuations { get; set; }
}

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

    [ForeignKey(typeof(Stock))]     // Specify the foreign key
    public string StockUUID { get; set; }
    public DateTime Time { get; set; }
    public decimal Price { get; set; }

    [ManyToOne]      // Many to one relationship with Stock
    public Stock Stock { get; set; }
}

Answer

redent84 picture redent84 · Aug 22, 2015

A ForeignKey always references the PrimaryKey of another class. In this case, your PrimaryKey is an integer, but you are trying to reference another property of type string. This is not supported, so you either reference the primary key, or you make the UUID property primary key.

public class Stock
{
    [PrimaryKey]
    public string UUID { get; set; } 
    [MaxLength(8)]
    public string Symbol { get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]      // One to many relationship with Valuation
    public List<Valuation> Valuations { get; set; }
}