zoukankan      html  css  js  c++  java
  • 一步步学习EF Core(1.DBFirst)

    前言

    很久没写博客了,因为真的很忙,终于空下来,打算学习一下EF Core顺便写个系列, 今天我们就来看看第一篇DBFirst.

     本文环境:VS2017  Win7  .NET Core1.1    EF Core1.1.2

    正文

    这里我们不讨论是用DBFirst好,还是CodeFirst高端..各有各自的用处和适用场景..

    我们单纯的只是来使用这个DBFirst..

    既然是DBFirst,那么在用DBFirst之前..首先你要有一个数据库(嗯,废话)

    其次,如果你是Windows7系统 那么需要升级你的Windows PowerShell到3.0+的版本

    然后你需要安装相关的工具包,从NuGet下载即可如下图:

    为了方便你们复制..我列一下:

    Microsoft.EntityFrameworkCore

    Microsoft.EntityFrameworkCore.SqlServer

    Microsoft.EntityFrameworkCore.Tools

    Microsoft.EntityFrameworkCore.Design

    Microsoft.EntityFrameworkCore.SqlServer.Design

    然后,我们在VS的工具选项中,选择NuGet包管理器,选择程序包管理控制台

    输入命令行:

    Scaffold-DbContext "这里输入你的数据库连接字符串" Microsoft.EntityFrameworkCore.SqlServer

    就会生成一个Modles文件夹如图:

    这里面就是你的上下文对象和相关的实体类了.

    我们进到上下文对象,会发现自己的连接字符串是固化在这里面的,如图:

    我们当然不能这么做,所以,请删除掉他.

    下一步,我们使用Asp.net Core 来测试测试看能不能访问.

    创建Core项目的流程,我就不说了

    然后给你的Core项目用NuGet添加引用:Microsoft.EntityFrameworkCore.SqlServer和Microsoft.EntityFrameworkCore

    在配置文件里添加数据库连接字符串:

      "ConnectionStrings": {
        "SchoolConnection": "Data Source=.;Initial Catalog=School_Test;User ID=**;Password=***;MultipleActiveResultSets=true"
      }

    然后我们在Startup中注入我们的上下文对象:

    在ConfigureServices()方法中注入,代码如下:

            public void ConfigureServices(IServiceCollection services)
            {
                // Add framework services.
                //注入SignalR.(与本文无关,请无视)
                services.AddSignalR(options =>
                {
                    options.Hubs.EnableDetailedErrors = true;
                });
               //注入上下文对象
                services.AddDbContext<School_TestContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("SchoolConnection")));
                services.AddMvc();
            }

    我们创建控制器,代码如下:

        public class TestController : Controller
        {
            //构造函数注入上下文
            private readonly School_TestContext _context;
            public TestController(School_TestContext Context)
            {
                _context = Context;
            }
    
    
            public IActionResult ListView()
            {
                return View(_context.UserTable.ToList());
            }
        }

    创建相应的视图如下:

    @model IEnumerable<EFCoreModel.Modles.UserTable>
     @{
            ViewData["Title"] = "ListView";
            Layout = "~/Views/Shared/_Layout.cshtml";
    }
        <h2>ListView</h2>
    
    <p>
        <a asp-action="Create">Create New</a>
    </p>
    <table class="table">
        <thead>
            <tr>
                <th>
                    用户名
                </th>
                <th>
                    密码
                </th>
                <th>
                   ID
                </th>
                <th>
                   班级名
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.UserName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.PassWord)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Class.ClassName)
                    </td>
                    <td>
                        <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                        <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                        <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </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.

    这是因为我们通过DBFirst生成的上下文并不能直接拿来注入使用.我们需要改造一下,给上下文添加构造函数,如下:

            public School_TestContext(DbContextOptions options) :base(options)
            {
    
            }

    然后在运行我们的代码.得到结果如下:

    我们发现红框位置的作为关联表的班级名,并没有显示~,这个留待我们后面讲解.

  • 相关阅读:
    Eclipse安装Hadoop插件
    (转)Ubuntu14.0.4中hadoop2.4.0伪分布模式配置
    Hadoop--DataNode无法启动
    启动与关闭hadoop
    hadoop中执行命令时发生错误
    strings命令
    Deriving data from ElasticSearch Engine
    elasticsearch data importing
    reading words in your computer and changing to female voice, linux festival text2wave saving wav files
    DDNS client on a Linux machine
  • 原文地址:https://www.cnblogs.com/GuZhenYin/p/6857413.html
Copyright © 2011-2022 走看看