zoukankan      html  css  js  c++  java
  • 如何在ASP.NET Core中应用Entity Framework

    注:本文提到的代码示例下载地址> How to using Entity Framework DB first in ASP.NET Core

    如何在ASP.NET Core中应用Entity Framework

    首先为大家提醒一点,.NET Core和经典.NET Framework的Library是不通用的,包括Entity Framework!

    哪怎么办? 别急,微软为.NET Core发布了.NET Core版本的Entity Framework,具体配置方法与经典.NET Framework版本的稍有区别,下面的内容就为带领大家在ASP.NET Core中应用Entity Framework DB first。

    注:目前部分工具处于Preview版本,正式版本可能会稍有区别。 

    前期准备:

    1.推荐使用VS2015 Update3作为你的IDE,下载地址:www.visualstudio.com

    2.你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:www.microsoft.com/net/core

    3.你需要有一个Sql Server数据库。

    结构应该是这样的。

    复制代码
    CREATE DATABASE TestNetCoreEF 
    GO 
    USE TestNetCoreEF 
    GO 
    CREATE TABLE Student( 
        ID int identity primary key, 
        Name nvarchar(50), 
        Age int 
    ) 
      
    INSERT INTO Student VALUES('Bear',18) 
    INSERT INTO Student VALUES('Frank',20)
    复制代码

    创建项目

    在VS中新建项目,项目类型选在ASP.NET Core Web Application (.NET Core),输入项目名称为TestEFInNetCore

    接下来选择Web Application, 右侧身份认证选择:No Authentication

    安装Entity Framework

    打开Tool->NuGet Package Manager->Package Manager Console

     

    在Pack Manager Console中运行如下命令:

      Install-Package Microsoft.EntityFrameworkCore.SqlServer

      Install-Package Microsoft.EntityFrameworkCore.Tools –Pre

      Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

    打开Project.json,在节点tool中添加如下配置:

    "tools": { 
        "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final", 
        …………. 
    }

    这是VS会自动下载对应的包至你的本地,目前这个还是preview版本,正式版请关注:https://docs.efproject.net/en/latest/intro.html

    生成数据库Mapping

    在Pack Manager Console中于运行如下命令:

    Scaffold-DbContext "{Your DB connect string}" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

      {Your DB connect string}:你的数据库连接字符串

      Microsoft.EntityFrameworkCore.SqlServer:目标数据库为Sql Server

      -OutputDir Models: 生成的文件的存放目录,目前目录是根目录下的Models目录

    之后引擎会试图连接你的SQL Server 数据库,并生成文件在你指定的目录里。

    在目录中找到一个***Context.cs并打开它,你会发现一个如下方法,

    复制代码
    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(@"{your sql connect string}");
    }
    复制代码

    如自动生成代码里所写的warning一样,我们不应该把连接字符串放在这里。接下来的工作,让我们来从appsettings.json中读取配置。

    在***Context.cs中添加一个属性用来存放ConnectionString,另外我们需要重写OnConfiguring方法,完整的代码应该是这样:

    public static string ConnectionString { get; set; } 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
        optionsBuilder.UseSqlServer(ConnectionString); 
    }

    打开appSetting.json,添加如下代码:

    "ConnectionStrings": { 
        "TestNetCoreEF": "Data Source={your sql server host address};Initial Catalog=TestNetCoreEF;user id={your username};password={your password};" 
    },

    完整的代码应该像这样:

    复制代码
    { 
        "ConnectionStrings": { 
            "TestNetCoreEF": "Data Source={your sql server host address};Initial Catalog=TestNetCoreEF;user id={your username};password={your password};" 
        }, 
        "Logging": { 
            "IncludeScopes": false, 
            "LogLevel": { 
                "Default": "Debug", 
                "System": "Information", 
                "Microsoft": "Information" 
            } 
        } 
    }
    复制代码

    打开 Startup.cs,在ConfigureServices(IServiceCollection services)方法中添加如下代码:

    TestNetCoreEFContext.ConnectionString = Configuration.GetConnectionString("TestNetCoreEF"); 

    完整的代码应该是这样:

    复制代码
    public void ConfigureServices(IServiceCollection services) 
    { 
        //config the db connection string 
        TestNetCoreEFContext.ConnectionString = Configuration.GetConnectionString("TestNetCoreEF"); 
      
        // Add framework services. 
        services.AddMvc(); 
    }
    复制代码

    关于调用Entity Framework

    真的,相信我,跟之前一毛一样,真的一毛一样。

    Models.TestNetCoreEFContext context = new Models.TestNetCoreEFContext();
    
    var StudentList = context.Student.ToList();

    最后:完整的代码Sample以及如何运行它,请访问:How to using Entity Framework DB First in ASP.NET Core

    更多脚本样例, 访问微软One Code样例库:http://aka.ms/onescriptsamples 更多代码样例, 访问微软One Script样例库:http://aka.ms/onecodesamples
  • 相关阅读:
    Response.Redirect 打开新窗体的两种方法
    linux下coredump的产生及调试方法
    AlertDialog具体解释
    数据仓库与数据挖掘的一些基本概念
    JS中setTimeout()的使用方法具体解释
    iOS开发- 查询项目代码行数
    STM32学习之路-LCD(3)<显示图片>
    谷歌技术"三宝"之MapReduce
    [ffmpeg 扩展第三方库编译系列] 关于libvpx mingw32编译问题
    javascript笔记
  • 原文地址:https://www.cnblogs.com/lyl6796910/p/6648867.html
Copyright © 2011-2022 走看看