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

牧云@^-^@ 提交于 2020-06-11 05:22:48

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/32153336/how-to-specify-a-foreign-key-property-in-sqlite-net-extensions

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