.NETCore使用EntityFrameworkCore连接数据库生成实体

EF Core 通过数据库提供程序插件模型与 SQL Server/SQL Azure、SQLite、Azure Cosmos DB、MySQL、PostgreSQL 和更多数据库配合使用。

使用EF Core 的优点

Entity Framework (EF) Core 是轻量化、可扩展、开源和跨平台版的常用 Entity Framework 数据访问技术。

EF Core 可用作对象关系映射程序 (O/RM),这可以实现以下两点:

  • 使 .NET 开发人员能够使用 .NET 对象处理数据库。
  • 无需再像通常那样编写大部分数据访问代码。

在开始使用EF Core的时候我们需要在项目中引用一些包 使用NuGet管理器直接引入即可 包名如下:

 Micorsoft.EntityFrameworkCore:EF框架的核心包
 Micorsoft.EntityFrameworkCore.SqlServer:针对SqlServer数据库的扩展

 其他包是为了生成实体使用的。

EF Core不支持用于可视化设计器的DB模型和向导来创建类似于EF 6的实体和上下文类。所以我们需要使用命令来生成。

Scaffold-DbContext命令

Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>] 
                    [-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]

参数说明:

-OutputDir *** 实体文件所存放的文件目录
-ContextDir *** DbContext文件存放的目录
-Context *** DbContext文件名
-Schemas *** 需要生成实体数据的数据表所在的模式
-Tables *** 需要生成实体数据的数据表的集合
-DataAnnotations
-UseDatabaseNames 直接使用数据库中的表名和列名(某些版本不支持)
-Force 强制执行,重写已经存在的实体文件

在VS2019NuGet程序包管理器控制台运行如下命令:

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

,命令运行成功之后生成如下类  连接字符串在Context类里面

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer(@"Server=.;Database=CloudCollector;Trusted_Connection=True;");
            }
        }

  

 使用“new”的简单的 DbContext 初始化

在业务逻辑类里面使用using new DbContext 来初始化DbContext

 public Cloud Get(int id)
        {
            using (var db = new CloudCollectorContext())
            {
                var result = db.Clouds.Where(t => t.Status == 1&&t.Id==id).FirstOrDefault();
                return result;
            }
        }

ASP.NET Core 依赖关系注入中的 DbContext

在.NetCore中开发要求需要IOC 所以我们需要在MVC的Startup的ConfigureServices方法中注册DbContext 注册代码如下

 services.AddDbContext<CloudCollectorContext>(
        options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));

appsettings.json文件配置如下:

"ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=CloudCollector;Trusted_Connection=True;"
  }

如此我们便可以使用依赖注入方式实现DbContext初始化了

public Cloud Get(int id)
        {
            var result=_context.Clouds.Where(t => t.Status == 1 && t.Id == id).FirstOrDefault();
            return result;
        }

 整个EFCore连接数据库初始化DbContext的方法就这样完成了。

原文地址:https://www.cnblogs.com/widows/p/14214565.html