【发布时间】:2026-01-26 01:50:01
【问题描述】:
如何指定引用特定属性而不是主键的外键?
例如 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(typeof(Stock))] 这引用了 ID 属性,但我需要让它引用 UUID 属性。
-
看看这可能会帮助你link
-
谢谢,这不是我所需要的,但它是有用的信息。