我的ASP.NET CORE MVC应用程序中有一个非常基本的任务。所以事情是我有2个模型订阅和优惠券 ,他们有一对多的关系,通过使用以下模型类和脚手架,我能够在优惠券创建页面上生成dropDownList ,以选择当前在数据库中的任何订阅。我也在为我的数据库和脚手架使用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; }
}
现在我想在我的注册页面上同样下拉,我正在使用个人用户帐户的内置注册系统,我只想在优惠券页面上包含相同的下拉菜单以选择“订阅”我想要相同的一个注册页面。我怎样才能做到这一点?与其他控制器(如“couponsController”)不同, AccountsController在其构造函数参数中没有获取任何ApplicationDbContext ,因此我无法确定如何在注册页面上从数据库中获取数据。
我知道以下代码有助于获取订阅列表并从中获取特定属性。
// GET: Coupons/Create
public IActionResult Create()
{
ViewData["SubscriptionId"] = new SelectList(_context.Subscription, "ID", "Identifier");
return View();
}
我想在我的注册页面上使用相同类型的东西但是在AccountsController上不存在dbcontext而且我无法新建它bcz我不知道在构造函数中提供什么选项。
如果你已经有了DbContext,那么只要你创建一个类似于你的其他控制器的构造函数,就应该自动注入它。
private ApplicationDbContext _db;
public AccountsController(ApplicationDbContext db)
{
_db = db;
}
然后你可以通过它访问你的DbSet。如果那不起作用,那么检查你的Startup类中的ConfigureServices中是否有类似的东西:
services.AddTransient<ApplicationDbContext>();
如果您的其他控制器可以访问DbContext,那么类似于该行的内容应该已存在。