ef core 读取数据上下文配置的问题

实在不知配置错误在哪里,求大牛帮忙看看!

报错信息
StartUp配置信息
数据库连接
上下文

一.新建一个.net core的MVC项目

          新建好项目后,不能像以前一样直接在新建项中添加ef,

          需要用命令在添加ef的依赖

二.EF Core实体框架核心安装:

工具> NuGet软件包管理器>软件包管理器控制台

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

  安装成功后就可以在Nuget依赖项中看到

四.更具一个命令就可以从数据库生成model了

  方式一:(通过现有数据库创建模型)

Scaffold-DbContext "Server=.;Database=Food;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

    该命令会在Models文件夹下生成数据库中的表和上下文对象

                 注:执行这一步的时候出现了点问题 ,因为系统是win7,powershell版本太低了,不支持这个命令,需要安装

                    3.0以上的powershell版本才行         



        添加成功后在models可以看到, 生成了上下文对象与和表对应的model





     现在就可以使用EF了

复制代码
public IActionResult Index()
{

        FoodContext fc = new FoodContext();

        List<ProType> ptlist = fc.ProType.ToList();

        ViewBag.ptlist = ptlist;

        return View();
    }

复制代码
 方式二:(通过模型创建数据库)

    1.创建上下文类

复制代码
public class FoodContext : DbContext
{
public FoodContext (DbContextOptions options)
: base(options)
{ }

public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }

}

public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }

public List< Post > Posts { get; set; }
}

public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }

public int BlogId { get; set; }
public Blog Blog { get; set; }
}
复制代码
    2.在startup.cs的ConfigureServices方法中中将上下文类注册为全局服务:
        services.AddDbContext(options => options.UseSqlServer(connection));

    3.在appsetting文件中增加连接字符串connection

    4.创建数据库
      工具 - > NuGet软件包管理器 - >软件包管理器控制台
      //创建模型的初始表
      Add-Migration InitialCreate
      //将新迁移应用于数据库
      Update-Database

五.使用依赖注入来装载EF的上下文对象

            .net core中用了不少的依赖注入,官方文档中也推荐使用           

             1:删除方法

复制代码
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@"Server=.;Database=Food;Trusted_Connection=True;");
}
复制代码
     2:添加方法

 public FoodContext(DbContextOptions<FoodContext> options)
        : base(options)
    {

    }

    添加的是一个构造函数用于注入

     3:在startup.cs的configureServices方法中添加依赖注入

复制代码
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();

        services.AddDbContext<FoodContext>(option => {
            option.UseSqlServer("Data Source =.; Initial Catalog = EFCore_dbfirst; User ID = sa; Password = sa.123");
        });

    }

复制代码