[英]3 table relationship
我正在嘗試在 c# 中建立 3 個表之間的關系我的模型是:吉他:
public class Guitar
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[MaxLength(30)]
[Required]
public string Model { get; set; }
public int? Price { get; set; }
[NotMapped]
public virtual Brand Brand { get; set; }
public int BrandId { get; set; }
牌:
public class Brand
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[NotMapped]
public virtual ICollection<Guitar> Guitars { get; set; }
public Brand()
{
Guitars = new HashSet<Guitar>();
}
購買:(此處可能缺少某些屬性)
public class Purchase
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
[MaxLength(40)]
public string BuyerName { get; set; }
[NotMapped]
public virtual Guitar Guitar { get; set; }
public int GuitarId { get; set; }
}
我已經設法將吉他和品牌表連接在一起,但我無法處理第三個。 到目前為止,這是我的代碼:
modelBuilder.Entity<Guitar>(entity =>
{
entity.HasOne(guitar => guitar.Brand)
.WithMany(brand => brand.Guitars)
.HasForeignKey(guitar => guitar.BrandId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
Purchases 表中的外鍵應該是吉他的 ID,但如果你有更好的主意,我願意接受。 那么,我如何對購買做同樣的事情呢?
從您的課程中刪除所有 [NotMapped],我也會添加買家 class
public class Guitar
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
....
[Required]
public int? BrandId { get; set; }
public virtual Brand Brand { get; set; }
}
public class Brand
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
.....
public virtual ICollection<Guitar> Guitars { get; set; }
public Brand()
{
Guitars = new HashSet<Guitar>();
}
}
public class Buyer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
[MaxLength(40)]
public string Name { get; set; }
public virtual ICollection<Purchase> Purchases { get; set; }
public Bayer()
{
Purchases = new HashSet<Purchase>();
}
}
public class Purchase
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
public int? BuyerId { get; set; }
public virtual Buyer Buyer { get; set; }
[Required]
public int? GuitarId { get; set; }
public virtual Guitar Guitar { get; set; }
}
如果您使用的是 net core 5+,則不需要任何流利的 api
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.