C# Entity Framework 依赖注入

本文详细介绍了如何在C#应用程序中结合Entity Framework实现依赖注入,通过示例代码展示了如何配置DI容器,将数据库上下文注入到控制器和服务中,以提升代码的可测试性和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace ConsoleApp6
{
    [Table("Books")]
    public class Book
    {
        public int BookId { get; set; }
        [Required]
        [StringLength(50)]
        public String Title { get; set; }

        [StringLength(50)]
        public String Publisher { get; set; }
    }
}

namespace ConsoleApp6
{
    public class BooksContext:DbContext
    {
        public BooksContext(DbContextOptions<BooksContext> options) : base(options) { }

        public DbSet<Book> Books { get; set; }

     
    }
}

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp6
{
    public class BooksService
    {
        private readonly BooksContext booksContext;

        public BooksService(BooksContext context) => booksContext = context;

        public async Task AddBooksAsync()
        {
            var b1 = new Book
            {
                Title = "New one",
                Publisher = "new p"

            };

            var b2 = new Book
            {
                Title = "new Two",
                Publisher = "new p2"
            };

            var b3 = new Book
            {
                Title = "new three",
                Publisher = "new p3"
            };

            await booksContext.AddRangeAsync(b1, b2, b3);


            int records = await booksContext.SaveChangesAsync();

            Console.WriteLine($"{records} records added");

            Console.WriteLine();

        }


        public async Task ReadBooksAsync()
        {
            List<Book> books = await booksContext.Books.ToListAsync();

            foreach (var b in books)
            {
                Console.WriteLine($"{b.Title}   {b.Publisher}");

            }

            Console.WriteLine();

        }


    }
}

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;


namespace ConsoleApp6
{
    class Program
    {
        static async Task Main(string[] args)
        {
            InitialzeService();
            ConfigureLogging();
            var services = Container.GetService<BooksService>();
            await services.AddBooksAsync();
            await services.ReadBooksAsync();
            Console.ReadKey();
        }

        public static ServiceProvider Container { get; private set; }
        private static void InitialzeService()
        { 
            const string ConnectionString =
                @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=WroxBooks;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

            var services = new ServiceCollection();
            services.AddTransient<BooksService>()
                .AddEntityFrameworkSqlServer()
                .AddDbContext<BooksContext>(option =>
                option.UseSqlServer(ConnectionString));

            Container = services.BuildServiceProvider();


    }

        private static void ConfigureLogging()
        {
            ILoggerFactory logger = Container.GetService<ILoggerFactory>();
            logger.AddConsole(LogLevel.Information);
        
        }

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值