【问题标题】:issue with new create dbcontext class object in asp.net core 2.1在 asp.net core 2.1 中新创建 dbcontext 类对象的问题
【发布时间】:2020-09-10 05:42:59
【问题描述】:

我是 .net core 2.1 的新手

我正在使用代码优先方法使用 .net core 2.1

问题是当我创建一个新对象 dbcontext 类然后给出错误见下一行

dbcontextstudent db=new dbcontextstudent();  //here give an red line

appsettings.json

 },
  "ConnectionStrings": {
    "sqlserverconn": "Server=DEVISSHAHID; Database=studdbs; User id=xxxx;Password=xxxxx;"
  },

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            //connection string
            services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));

student.cs

namespace WebApplication1.Models
{
    public class student
    {
        [Key]
        public int studid { get; set; }

        public string studname { get; set; }

        public string studsalary { get; set; }

        public int studage { get; set; }
    }
}

dbcontextstudent.cs

namespace WebApplication1.Models
{
    public class dbcontextstudent : DbContext
    {
        public dbcontextstudent(DbContextOptions<dbcontextstudent> options) : base(options)
        {

        }

        public DbSet<student> stud { get; set; }
    }
}

HomeController.cs

上面的智能没看懂

我按照智能感知编写代码,但仍然报错我知道错误很明显但没有解决

我在哪个地方做错了?

【问题讨论】:

    标签: entity-framework asp.net-core model-view-controller


    【解决方案1】:

    您必须将您的DbContext 类型传递给ConfigureServices 方法中的AddDbContext 方法,如下所示:

                services.AddDbContext<dbcontextstudent>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));
    
    

    之后,你就在依赖注入中注册了dbcontextstudent类。

    您不应该像以前那样自行创建dbcontextstudent 的实例:

    dbcontextstudent db=new dbcontextstudent();
    

    相反,您可以通过控制器的构造函数注入它,如下所示:

    public HomeController : Controller 
    {
       private readonly dbcontextstudent _db;
    
       public HomeController(dbcontextstudent db)
       {
         _db = db;
        }
    
    ... and then you can use the _db variable in your post action
    }
    

    【讨论】:

    • 我仍然面临 dbcontext 错误i.stack.imgur.com/j7P3c.png
    • 我更新了我的答案,HomeControllerConfgureServices 都需要调整
    • 请你能帮助更多我面临一个错误i.stack.imgur.com/fY9Fs.png请帮助
    • 您可以为此提出一个新问题吗?这是一个单独的问题
    • 错误已解决,只需在上下文类中添加这一行Database.EnsureCreated(); 感谢您的时间
    猜你喜欢
    • 2019-08-29
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多