私は私のASP.NET CORE MVCアプリケーションで非常に基本的なタスクを持っています。だから私は2つのモデルのサブスクリプションとクーポンがあり、彼らは1 対多の関係を持っており、次のモデルクラスと足場を使って 、クーポンのドロップダウンリストを生成して、現在データベースにあるサブスクリプションの誰かを選択するページを作成することができました。私はdbと足場のためにEntity Frameworkを使用しています。
モデルクラス
public class Subscription
{
public string FirstName { get; set; }
[Key]
public int ID { get; set; }
[Required]
public string Identifier { get; set; }
public bool State { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int MonthlyPrice { get; set; }
[Required]
public int MinMonthlyPrice { get; set; }
[Required]
public int MonthlyDiscount { get; set; }
public virtual ICollection<Coupon> Coupons { get; set; }
public virtual ICollection<RegisterViewModel> Registrations { get; set; }
}
public class Coupon
{
[Required]
public string CouponCode { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
[Key]
public int ID { get; set; }
public int Discount { get; set; }
public bool IsPercentage { get; set; }
[ForeignKey("Identifier")]
public int SubscriptionId { get; set; }
public virtual Subscription Identifier { get; set; }
[Required]
public int ValidMonths { get; set; }
public bool IsSponsored { get; set; }
[Required]
public int Length { get; set; }
[Required]
public int Quantity { get; set; }
}
今私は登録ページに同じドロップダウンをしたい、私は個々のユーザーアカウントの組み込みの登録システムを使用しているだけで、私はクーポンページで同じサブスクリプションを選択するために持っている同じドロップダウンを含める登録ページ。どうやってやるの? AccountsControllerは、 "couponsController"のような他のコントローラとは異なり、コンストラクタパラメータでApplicationDbContextを取得していないため、登録ページでデータベースからデータを取得する方法がわかりません。
私は、次のコードは私にサブスクリプションリストを取得し、それから特定のプロパティのみを取得するのに役立つことを知っています。
// GET: Coupons/Create
public IActionResult Create()
{
ViewData["SubscriptionId"] = new SelectList(_context.Subscription, "ID", "Identifier");
return View();
}
登録ページに同じ種類のものが必要ですが、dbcontextはAccountsControllerには存在せず、bczを新しくできません。コンストラクタでどのようなオプションを提供するのか分かりません。
あなたのDbContextを既にお持ちの場合は、他のコントローラに似たコンストラクタを作成するだけで自動的に注入されるはずです。
private ApplicationDbContext _db;
public AccountsController(ApplicationDbContext db)
{
_db = db;
}
それから、あなたはそれを通してあなたのDbSetsにアクセスすることができます。それがうまくいかない場合は、StartupクラスのConfigureServicesに類似したものがあるかどうかを確認してください:
services.AddTransient<ApplicationDbContext>();
あなたの他のコントローラがDbContextへのアクセス権を持っていれば、その行に似た何かがすでに存在しているはずです。