当前位置:首页 > 数据库 > SQlite

CodeGo.net>如何在SQLite-Net扩展中指定外键属性

如何在SQLite-Net扩展中指定外键属性' />

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

例如,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; }
}

解决方法:

一个ForeignKey总是引用另一个类的PrimaryKey.在这种情况下,您的PrimaryKey是一个整数,但是您尝试引用字符串类型的另一个属性.不支持此功能,因此您可以引用主键,或者将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; }
}

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!