栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

EFcore 依赖注入

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 options)
            : base(options)
        {
        }

        public virtual DbSet Contacts { get; set; }
        public virtual DbSet UserInfos { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasAnnotation("Relational:Collation", "Chinese_PRC_CI_AS");

            modelBuilder.Entity(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(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(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 _logger;
        private readonly ExampleContext _db;

        public HomeController(ILogger logger,ExampleContext exampleContext)
        {
            _logger = logger;
            _db = exampleContext;
        }

        public IActionResult Index()
        {
            var query = _db.UserInfos.Find(1);
            return View();
        }      
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984496.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号