创建.net core ef项目

建一个model类库的项目

 

点击工具->nuget包管理器->程序包管理器控制台(默认项目选择Model,最好将Model设置为启动项目)

依次输入以下命令

            1.Install-Package Microsoft.EntityFrameworkCore.SqlServer

            2.Install-Package Microsoft.EntityFrameworkCore.Tools

            3.Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

       4.Scaffold-DbContext "server=.;database=ConCard;uid=sa;pwd=123123;" Microsoft.EntityFrameworkCore.SqlServer -O Models -F  //密码连接

    Scaffold-DbContext "Server=.;Database=MyData;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models  //本地连接

第4步是连接数据库生成实体类,后边的-O Models -F也有写作-OutputDir Models -Force的;-o (OutputDir) 指定用于输出类的目录  -f (Force) 生成时覆盖现有文件 -Context 指定生成的DbContext类的名称,省略的话按数据库名称生成DbContext类文件

运行完成后会自动一个Models文件夹,文件夹下有实体类和Context类。

生成后的context文件如下:

 

警告信息翻译后:若要保护连接字符串中潜在的敏感信息,应将其移出源代码。通过使用Name=语法从配置中读取连接字符串,可以避免构建连接字符串

构建连接字符串:在Context.cs注释掉OnConfiguring方法、在appsettings.json添加连接字符串、在Startup.cs的ConfigureServices增加AddDbContext,但是运行时在context.Add(table)这一步报错(错误信息:No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.),还是改回上一步的了

 

参考:创建ef core项目 https://blog.csdn.net/zhouxueli32/article/details/80390650

  创建ef core项目 https://blog.csdn.net/qq_25086397/article/details/88941513

  创建ef core+di项目 https://www.cnblogs.com/han1982/p/11058788.html

  构建连接字符串:https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/connection-strings

 

posted @ 2020-11-20 09:18  户的博客  阅读(407)  评论(0编辑  收藏  举报