EFcore 依赖注入

2023-10-21 23:08
文章标签 依赖 注入 efcore

本文主要是介绍EFcore 依赖注入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基于EFcore 采用DBFirst模式 实现DBContext依赖注入

1.SQL Server创建数据库

创建一个名为Example的数据库,并含有UserInfo、Contacts数据表

UserInfo字段:
在这里插入图片描述
Contacts字段
在这里插入图片描述

2.VS引入Nuget程序包

在这里插入图片描述
可以在程序包管理控制台 手动键入命令行安装Nuget包:

install-package microsoft.entityframeworkcore
install-package microsoft.entityframeworkcore.sqlserver
install-package mircosoft.entityframeworkcore.tools

3.Scaffold-DbContext框架生成Model

Scaffold-DBContext “server=.;database=Example;uid=sa;pwd=sa123456” microsoft.entityframeworkcore.sqlserver -outputDir Models

命令行说明:
在这里插入图片描述
框架Build Succeed后,自动生成数据库实体类与DbContext类

UserInfo:

namespace WebApplication24.Models
{public partial class UserInfo{public int Id { get; set; }public string Name { get; set; }public int? Age { get; set; }}
}

Contact:

namespace WebApplication24.Models
{public partial class Contact{public int Id { get; set; }public string Name { get; set; }public string Phone { get; set; }public string Address { get; set; }}
}

ExampleContext:

namespace WebApplication24.Models
{public partial class ExampleContext : DbContext{public ExampleContext(){}public ExampleContext(DbContextOptions<ExampleContext> options): base(options){}public virtual DbSet<Contact> Contacts { get; set; }public virtual DbSet<UserInfo> UserInfos { get; set; }protected override void OnModelCreating(ModelBuilder modelBuilder){modelBuilder.HasAnnotation("Relational:Collation", "Chinese_PRC_CI_AS");modelBuilder.Entity<Contact>(entity =>{entity.Property(e => e.Id).ValueGeneratedNever().HasColumnName("ID");entity.Property(e => e.Address).HasMaxLength(50);entity.Property(e => e.Name).HasMaxLength(50);entity.Property(e => e.Phone).HasMaxLength(50);});modelBuilder.Entity<UserInfo>(entity =>{entity.ToTable("UserInfo");entity.Property(e => e.Id).ValueGeneratedNever().HasColumnName("ID");entity.Property(e => e.Name).HasMaxLength(50);});OnModelCreatingPartial(modelBuilder);}partial void OnModelCreatingPartial(ModelBuilder modelBuilder);}
}

4.依赖注入DBContext

Startup类中依赖注入

public void ConfigureServices(IServiceCollection services)
{services.AddControllersWithViews();services.AddDbContext<ExampleContext>(options => {options.UseSqlServer(Configuration.GetConnectionString("defaultConnection"));});
}

appsettings.json中加入连接字符串

"ConnectionStrings": {"defaultConnection": "server=.;database=example;uid=sa;pwd=sa123456"}

AddDbContext解释摘要:

摘要://     Registers the given context as a service in the Microsoft.Extensions.DependencyInjection.IServiceCollection.//     Use this method when using dependency injection in your application, such as//     with ASP.NET Core. For applications that don't use dependency injection, consider//     creating Microsoft.EntityFrameworkCore.DbContext instances directly with its//     constructor. The Microsoft.EntityFrameworkCore.DbContext.OnConfiguring(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)//     method can then be overridden to configure a connection string and other options.//     For more information on how to use this method, see the Entity Framework Core//     documentation at https://aka.ms/efdocs. For more information on using dependency//     injection, see https://go.microsoft.com/fwlink/?LinkId=526890.

5.DBContext构造函数注入

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using WebApplication24.Models;namespace WebApplication24.Controllers
{public class HomeController : Controller{private readonly ILogger<HomeController> _logger;private readonly ExampleContext _db;public HomeController(ILogger<HomeController> logger,ExampleContext exampleContext){_logger = logger;_db = exampleContext;}public IActionResult Index(){var query = _db.UserInfos.Find(1);return View();}      }
}

这篇关于EFcore 依赖注入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/257519

相关文章

SQL注入漏洞扫描之sqlmap详解

《SQL注入漏洞扫描之sqlmap详解》SQLMap是一款自动执行SQL注入的审计工具,支持多种SQL注入技术,包括布尔型盲注、时间型盲注、报错型注入、联合查询注入和堆叠查询注入... 目录what支持类型how---less-1为例1.检测网站是否存在sql注入漏洞的注入点2.列举可用数据库3.列举数据库

Spring核心思想之浅谈IoC容器与依赖倒置(DI)

《Spring核心思想之浅谈IoC容器与依赖倒置(DI)》文章介绍了Spring的IoC和DI机制,以及MyBatis的动态代理,通过注解和反射,Spring能够自动管理对象的创建和依赖注入,而MyB... 目录一、控制反转 IoC二、依赖倒置 DI1. 详细概念2. Spring 中 DI 的实现原理三、

python中poetry安装依赖

《python中poetry安装依赖》本文主要介绍了Poetry工具及其在Python项目中的安装和使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录前言1. 为什么pip install poetry 会造成依赖冲突1.1 全局环境依赖混淆:1

每天认识几个maven依赖(ActiveMQ+activemq-jaxb+activesoap+activespace+adarwin)

八、ActiveMQ 1、是什么? ActiveMQ 是一个开源的消息中间件(Message Broker),由 Apache 软件基金会开发和维护。它实现了 Java 消息服务(Java Message Service, JMS)规范,并支持多种消息传递协议,包括 AMQP、MQTT 和 OpenWire 等。 2、有什么用? 可靠性:ActiveMQ 提供了消息持久性和事务支持,确保消

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip

深入理解数据库的 4NF:多值依赖与消除数据异常

在数据库设计中, "范式" 是一个常常被提到的重要概念。许多初学者在学习数据库设计时,经常听到第一范式(1NF)、第二范式(2NF)、第三范式(3NF)以及 BCNF(Boyce-Codd范式)。这些范式都旨在通过消除数据冗余和异常来优化数据库结构。然而,当我们谈到 4NF(第四范式)时,事情变得更加复杂。本文将带你深入了解 多值依赖 和 4NF,帮助你在数据库设计中消除更高级别的异常。 什么是

PHP防止SQL注入详解及防范

SQL 注入是PHP应用中最常见的漏洞之一。事实上令人惊奇的是,开发者要同时犯两个错误才会引发一个SQL注入漏洞。 一个是没有对输入的数据进行过滤(过滤输入),还有一个是没有对发送到数据库的数据进行转义(转义输出)。这两个重要的步骤缺一不可,需要同时加以特别关注以减少程序错误。 对于攻击者来说,进行SQL注入攻击需要思考和试验,对数据库方案进行有根有据的推理非常有必要(当然假设攻击者看不到你的

PHP防止SQL注入的方法(2)

如果用户输入的是直接插入到一个SQL语句中的查询,应用程序会很容易受到SQL注入,例如下面的例子: $unsafe_variable = $_POST['user_input'];mysql_query("INSERT INTO table (column) VALUES ('" . $unsafe_variable . "')"); 这是因为用户可以输入类似VALUE”); DROP TA

PHP防止SQL注入的方法(1)

(1)mysql_real_escape_string – 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集 使用方法如下: $sql = "select count(*) as ctr from users where username ='".mysql_real_escape_string($username)."' and password='". mysql_r

PHP7扩展开发之依赖其他扩展

前言 有的时候,我们的扩展要依赖其他扩展。比如,我们PHP的mysqli扩展就依赖mysqlnd扩展。这中情况下,我们怎么使用其他扩展呢?这个就是本文讲述的内容。 我们新建立一个扩展,名字叫 demo_dep , 依赖之前的say扩展。 在demo_dep扩展中,我们实现demo_say方法。这个方法调用say扩展的say方法。 代码 基础代码 确保say扩展的头文件正确安装到了php