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 注入攻击(SQL Injection)原理、利用方式与防御策略深度解析

《SQL注入攻击(SQLInjection)原理、利用方式与防御策略深度解析》本文将从SQL注入的基本原理、攻击方式、常见利用手法,到企业级防御方案进行全面讲解,以帮助开发者和安全人员更系统地理解... 目录一、前言二、SQL 注入攻击的基本概念三、SQL 注入常见类型分析1. 基于错误回显的注入(Erro

python依赖管理工具UV的安装和使用教程

《python依赖管理工具UV的安装和使用教程》UV是一个用Rust编写的Python包安装和依赖管理工具,比传统工具(如pip)有着更快、更高效的体验,:本文主要介绍python依赖管理工具UV... 目录前言一、命令安装uv二、手动编译安装2.1在archlinux安装uv的依赖工具2.2从github

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

javacv依赖太大导致jar包也大的解决办法

《javacv依赖太大导致jar包也大的解决办法》随着项目的复杂度和依赖关系的增加,打包后的JAR包可能会变得很大,:本文主要介绍javacv依赖太大导致jar包也大的解决办法,文中通过代码介绍的... 目录前言1.检查依赖2.更改依赖3.检查副依赖总结 前言最近在写项目时,用到了Javacv里的获取视频

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Spring-DI依赖注入全过程

《Spring-DI依赖注入全过程》SpringDI是核心特性,通过容器管理依赖注入,降低耦合度,实现方式包括组件扫描、构造器/设值/字段注入、自动装配及作用域配置,支持灵活的依赖管理与生命周期控制,... 目录1. 什么是Spring DI?2.Spring如何做的DI3.总结1. 什么是Spring D

Springboot项目构建时各种依赖详细介绍与依赖关系说明详解

《Springboot项目构建时各种依赖详细介绍与依赖关系说明详解》SpringBoot通过spring-boot-dependencies统一依赖版本管理,spring-boot-starter-w... 目录一、spring-boot-dependencies1.简介2. 内容概览3.核心内容结构4.

Java Spring的依赖注入理解及@Autowired用法示例详解

《JavaSpring的依赖注入理解及@Autowired用法示例详解》文章介绍了Spring依赖注入(DI)的概念、三种实现方式(构造器、Setter、字段注入),区分了@Autowired(注入... 目录一、什么是依赖注入(DI)?1. 定义2. 举个例子二、依赖注入的几种方式1. 构造器注入(Con

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter