我有一個 Currency 物件和一個 Product 物件。我需要將貨幣鏈接到 WholesaeCurrency 以及 Product 物件的 RetailCurrency 欄位
public class Currency
{
/// <summary>
/// Id is the 3 character ISO currency code
/// </summary>
[StringLength(3)]
public string Id { get; set; }
[StringLength(100)]
public string Name { get; set; }
}
我有另一個帶有 2 個貨幣欄位的物件:
public class Product
{
public int Id { get; set; }
public decimal WholesaleRate { get; set; }
public string WholesaleCurrencyId { get; set; }
public virtual Currency WholesaleCurrency { get; set; }
public decimal RetailRate { get; set; }
public string RetailCurrencyId { get; set; }
public virtual Currency RetailCurrency { get; set; }
}
我的查詢是:
- 這兩個物件之間有什么關系?一對多還是一對一?
- 我如何表達這些關系?以上是正確的嗎?
uj5u.com熱心網友回復:
您可以嘗試以下演示:
貨幣:
public class Currency
{
/// <summary>
/// Id is the 3 character ISO currency code
/// </summary>
[StringLength(3)]
public string Id { get; set; }
[StringLength(100)]
public string Name { get; set; }
public virtual ICollection<Product> ProductWholesale { get; set; }
public virtual ICollection<Product> ProductRetail { get; set; }
}
在產品中:
public class Product
{
public int Id { get; set; }
public decimal WholesaleRate { get; set; }
public string WholesaleCurrencyId { get; set; }
public virtual Currency WholesaleCurrency { get; set; }
public decimal RetailRate { get; set; }
public string RetailCurrencyId { get; set; }
public virtual Currency RetailCurrency { get; set; }
}
在您的背景關系中添加以下代碼:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasOne(p => p.WholesaleCurrency)
.WithMany(t => t.ProductWholesale)
.HasForeignKey(m => m.WholesaleCurrencyId )
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Product>()
.HasOne(p => p.RetailCurrency)
.WithMany(t => t.ProductRetail)
.HasForeignKey(m => m.RetailCurrencyId)
.OnDelete(DeleteBehavior.Restrict);
}
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494610.html
