如何在SQLite-Net Extensions中指定外键属性

时间:2015-08-22 06:58:47

标签: c# sqlite-net-extensions

如何指定引用特定属性而不是主键的外键?

例如,Stock类具有uuid属性。我想在Valuation类中创建一个使用此属性引用它的外键。

在下面的示例中,[ForeignKey(typeof(Stock))]行引用了Stock类的ID属性,但我需要它来引用UUID属性。

我该怎么做?

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; }
}

1 个答案:

答案 0 :(得分:4)

ForeignKey始终引用另一个类的PrimaryKey。在这种情况下,您的PrimaryKey是一个整数,但您尝试引用另一个string类型的属性。这不受支持,因此您可以引用主键,也可以创建UUID属性主键。

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; }
}