.NET 8 中 Entity Framework Core 的使用

本文代码:https://download.csdn.net/download/hefeng_aspnet/89935738

概述

Entity Framework Core (EF Core) 已成为 .NET 开发中数据访问的基石工具,为开发人员提供了强大而多功能的解决方案。随着 .NET 8 和 C# 10 中引入的改进,开发人员现在可以使用更丰富的功能和增强功能,从而进一步增强了 EF Core 的功能。

在本综合指南中,我们将深入探讨 Entity Framework Core,从基本概念到高级技术。我们深入研究 EF Core 的复杂性,利用 C# 10 和 .NET 8 的最新功能,为开发人员提供有效使用 EF Core 所需的知识和技能。

在本指南中,我们旨在让开发人员深入了解 Entity Framework Core,使他们能够在 .NET 生态系统中构建高效、可扩展且可维护的数据驱动应用程序。无论您是新手还是经验丰富的用户,本指南都将帮助您在我们的 .NET 项目中充分发挥 Entity Framework Core 的潜力。

Entity Framework Core 入门

我们这些希望在 .NET 中构建数据驱动应用程序的开发人员必须从 Entity Framework Core (EF Core) 开始。EF Core 是一个轻量级、可扩展、跨平台的 ORM(对象关系映射器)框架,可简化数据访问和操作,为开发人员提供众多好处。

它抽象了数据库交互的复杂性,允许开发人员使用熟悉的 C# 语法处理实体和关系,这是 EF Core 的主要优势之一。通过提供对底层数据库的高级抽象,EF Core 简化了开发并减少了数据访问所需的样板代码量。

在 .NET 8 项目中安装 EF Core 后,开发人员可以使用 EF Core API 来定义数据库上下文、实体和关系。安装后,开发人员可以使用 EF Core API 来配置关系。在 EF Core 中,DbContext 类表示数据库会话并提供对 DbSet 属性的访问,从而实现与实体的交互。

// Example: Creating a DemoDbContext class the file is kept in DbContext Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data;

public class DemoDbContext: DbContext

{

public DemoDbContext(DbContextOptions options) : base(options)

{

}

public DbSet<User> Users { get; set; }

// Other DbSet properties for additional entities

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer("OurConnectionString");

}

}

MyDbContext 类继承自 DbContext,并为 User 实体定义一个 DbSet 属性。OnConfiguring 方法将 EF Core 配置为使用 SQL Server 作为数据库提供程序,并指定连接字符串。

使用 EF Core,开发人员可以在设置数据库上下文后执行 CRUD 操作(创建、读取、更新、删除)。在 CRUD 操作中,操作实体对象,并在 DbContext 的 DbSet 属性上调用 Add、Find、Update 和 Remove 等方法。

因此,开始使用 Entity Framework Core 需要在 .NET 项目中进行设置,定义数据库上下文、实体和关系,并使用 EF Core API 执行 CRUD 操作。开发人员可以使用 EF Core 在 .NET 中更高效、更有效地构建数据驱动的应用程序。

使用 LINQ 查询数据

在 Entity Framework Core (EF Core) 中,使用 LINQ(语言集成查询)可让您从数据库中检索数据并使用 C# 语法对其进行操作。为了高效且有效地与数据库交互,开发人员可以编写富有表现力且可读的 LINQ 查询来过滤、排序和投影数据。

我们开发人员必须了解 LINQ 的基础知识以及它如何与 EF Core 集成,然后才能使用 EF Core 中的 LINQ 查询数据。C# 的 LINQ 语言扩展允许开发人员使用统一的语法从各种数据源查询数据。借助 EF Core,开发人员可以通过将 LINQ 查询转换为针对底层数据库执行的 SQL 查询,直观而熟悉地处理实体数据。

在 EF Core 中使用 LINQ 需要了解延迟执行的概念。在 EF Core 中,LINQ 查询是延迟执行的,这意味着它们不会在定义时立即执行,而是在访问或枚举查询结果时执行。通过延迟执行,开发人员可以构建复杂的查询并应用其他操作(例如过滤或排序),然后再对数据库执行这些操作。

IQueryable 表示可以在执行之前进一步修改或编写的查询,这是 EF Core 中 LINQ 的另一个关键功能。借助 IQueryable,开发人员可以根据运行时条件或用户输入动态构建查询,从而允许他们动态地过滤、排序和投影数据。

// Example: Creating a UserRepository class the file is kept in Repository Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Interfaces;

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data.Repository;

public class UserRepository : IUserRepository

{

private readonly DemoDbContext _dbContext;

private bool _disposed = false;

public UserRepository(DemoDbContext dbContext)

{

_dbContext = dbContext;

}

/// <summary>

/// This is an Example Querying data with LINQ

/// </summary>

/// <returns>List</returns>

public Task<List<User>> GetAllActiveUsersAsync() =>

_dbContext.Users

.Where(u => u.IsActive)

.OrderBy(u => u.LastName)

.ThenBy(u => u.FirstName)

.ToListAsync();

protected virtual void Dispose(bool disposing)

{

if (_disposed)

return;

if (disposing)

{

_dbContext.Dispose();

}

_disposed = true;

}

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

}

在上述代码示例中,LINQ 查询根据用户的年龄筛选用户,按姓氏排序,并仅选择用户的名字和姓氏。LINQ 运算符可以链接在一起以构建复杂的查询,这些查询可以使用 IQueryable 接口对数据库高效执行。

简而言之,在 EF Core 中使用 LINQ 查询数据是一种灵活而强大的与数据库交互的方式。通过了解 LINQ 语法、延迟执行和 IQueryable 接口,开发人员可以编写满足其应用程序需求的富有表现力且高效的查询。

使用迁移

为了管理数据库架构更改并确保一致性和完整性,使用 Entity Framework Core (EF Core) 中的迁移至关重要。开发人员可以使用迁移来随时间推移改进数据库架构,同时保留现有数据并确保版本之间的平稳过渡。

开发人员需要了解迁移的基础知识及其工作原理,才能开始使用 EF Core 迁移。通过使用迁移,开发人员可以使用 C# 代码定义和应用对数据库架构的更改,而不是手动更改数据库。这种方法的优点是可以控制数据库架构更改、重复数据库更新并自动化部署管道。

使用 Entity Framework Core,生成和应用迁移的过程非常简单。开发人员可以根据实体模型的更改生成迁移,并使用 CLI(命令行界面)将其应用于数据库。开发人员可以使用以下命令创建名为"InitialCreate"的新迁移:

dotnet ef migrations add InitialCreate

一旦生成迁移,开发人员就可以使用以下命令将其应用到数据库:

dotnet ef database update

EF Core 提供的内置工具还可用于管理 Visual Studio 2022 IDE 中的迁移。通过右键单击包含 DbContext 的项目并选择"添加 > 新脚手架项",开发人员可以选择"EF Core > 迁移"并按照提示创建新的迁移。同样,开发人员可以通过右键单击项目并选择"更新数据库"来应用迁移。

此外,除了管理架构更改之外,EF Core 迁移还支持数据迁移和播种初始数据。开发人员可以使用数据迁移在迁移过程中填充或转换数据,从而确保数据库在架构更改后保持一致。在迁移代码中,开发人员可以使用 migrationBuilder 对象执行 SQL 命令或操作数据。在 DbContext 的 OnModelCreating 方法中,播种初始数据涉及在创建或更新模型时将预定义数据插入数据库。

因此,在 EF Core 中使用迁移时,管理数据库架构更改、应用更新和确保数据一致性至关重要。通过了解迁移的基础知识并使用 Visual Studio 2022 IDE 和 EF Core 提供的工具,开发人员可以有效地管理数据库架构更改并维护其应用程序数据的完整性。

高级概念和技术

通过了解 Entity Framework Core (EF Core) 中的高级概念和技术,开发人员可以优化性能、实现复杂功能并优化其应用程序的效率。通过掌握这些技术并最大限度地发挥 EF Core 的潜力,开发人员可以构建高性能、可扩展的应用程序。

EF Core 提供三种加载策略:预先加载、延迟加载和显式加载。开发人员可以使用预先加载在单个查询中将相关实体与主实体一起加载,从而减少数据库往返次数。延迟加载仅在需要时加载数据,延迟加载会推迟加载相关实体,直到访问它们为止。开发人员可以指定何时显式加载相关实体,从而更有效地检索数据。

// Example: Creating a UserRepository class the file is kept in Models Folder in Project EntityFrameworkCoreGuideNET8.Domain

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

public record Order

{

Key

public Guid Id { get; init; }

public Guid UserId { get; init; }

ForeignKey("UserId")

public required User User { get; init; }

Required

public string ProductName { get; init; }=string.Empty;

Required,Range(0, double.MaxValue, ErrorMessage = "Price must be a positive value.")

public decimal Price { get; init; }

Required

public DateTime OrderDate { get; init; }

}

// Example: Creating a UserRepository class the file is kept in Repository Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Interfaces;

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data.Repository;

public class UserRepository : IUserRepository

{

private readonly DemoDbContext _dbContext;

private bool _disposed = false;

public UserRepository(DemoDbContext dbContext)

{

_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));

}

/// <summary>

/// This is an Example Querying data with LINQ

/// </summary>

/// <returns>List</returns>

public Task<List<User>> GetAllActiveUsersAsync() =>

_dbContext.Users

.Where(u => u.IsActive)

.OrderBy(u => u.LastName)

.ThenBy(u => u.FirstName)

.ToListAsync();

/// <summary>

/// This example is Eager loading in EF Core

/// </summary>

/// <returns></returns>

public Task<List<User>> LoadUsersWithOrdersAsync() =>

_dbContext.Users

.Include(u=>u.Orders)

.Where(u => u.IsActive)

.OrderBy(u => u.LastName)

.ThenBy(u => u.FirstName)

.ToListAsync();

protected virtual void Dispose(bool disposing)

{

if (_disposed)

return;

if (disposing)

{

_dbContext.Dispose();

}

_disposed = true;

}

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

}

为了在 EF Core 应用程序中保持数据一致性和完整性,事务至关重要。通过将多个数据库操作组合成一个原子工作单元,开发人员可以确保所有操作都成功,或者都不应用。除了防止数据损坏之外,这还可以确保数据库保持一致。

在使用存储过程和原始 SQL 查询时,EF Core 为开发人员提供了灵活性和性能优化机会。通过在存储过程中封装复杂的逻辑和业务规则,开发人员可以在提高性能的同时提高性能和安全性。为了获得更好的控制和性能优化,开发人员可以使用原始 SQL 查询直接对数据库执行 SQL 命令,从而绕过 EF Core 的查询转换机制。

通过使用缓存和批处理优化性能,可以显著提高 EF Core 应用程序的效率。开发人员可以将经常访问的数据缓存在内存中,从而减少需要进行的数据库查询次数并提高应用程序的响应能力。通过将多个数据库操作组合成一个批处理,批处理可以最大限度地减少往返次数,并通过最大限度地减少延迟来提高整体性能。

我们开发人员可以通过掌握 EF Core 中的高级概念和技术(例如加载策略、事务、存储过程、原始 SQL 查询、缓存和批处理)来构建高性能、可扩展的应用程序。借助这些技术,开发人员可以优化性能、实现复杂的功能并为他们的 EF Core 应用程序提供卓越的用户体验。

将 Entity Framework Core 与 ASP.NET Core 集成

Web 开发人员可以使用 ASP.NET Core 和 Entity Framework Core (EF Core) 构建可扩展且强大的 Web 应用程序。开发人员可以基于 ASP.NET Core 和 EF Core 的强大功能实施最佳实践和设计模式,从而确保其 API 的安全性、性能和可维护性。

实现存储库模式和工作单元是构建 RESTful API 的重要组成部分。存储库模式将应用程序的业务逻辑与数据访问逻辑分开。通过将数据访问操作封装在存储库中并在工作单元中协调事务,开发人员可以更好地分离关注点并提高代码的可测试性。

使用 EF Core 构建 API 需要处理并发和乐观锁定。多个用户可以尝试同时修改相同的数据,从而导致并发问题。开发人员可以通过实施乐观锁定机制(例如行版本控制或时间戳列)来优雅地检测和解决冲突,从而确保多用户环境中的数据完整性和一致性。

为了保护敏感信息并满足安全要求,授权和身份验证至关重要。 ASP.NET Core 提供了强大的身份验证和授权机制,包括 JWT(JSON Web 令牌)、OAuth 和 OpenID Connect。开发人员可以通过配置身份验证和授权策略,根据用户角色、权限和其他标准控制对 API 端点的访问。

// Example: is using Program.cs file is kept in Project EntityFrameworkCoreGuideNET8.Business.UI, which is ASP.net Core MVC Project

using EntityFrameworkCoreGuideNET8.Business.UI.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

// Example: Configuring authentication and authorization in ASP.NET Core

builder.Services.AddJwtAuthentication(builder.Configuration);

builder.Services.AddAdminAuthorization();

var app = builder.Build();

// Configure the HTTP request pipeline.

if (!app.Environment.IsDevelopment())

{

app.UseExceptionHandler("/Home/Error");

// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

app.UseHsts();

}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(

name: "default",

pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

// Example: Creating a JwtAuthentication.cs class the file is kept in Extensions Folder in Project EntityFrameworkCoreGuideNET8.Business.UI

using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.IdentityModel.Tokens;

using System.Text;

namespace EntityFrameworkCoreGuideNET8.Business.UI.Extensions;

public static class JwtAuthentication

{

public static void AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration)

{

// Example: Configuring authentication and authorization in ASP.NET Core

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

.AddJwtBearer(options =>

{

options.TokenValidationParameters = new TokenValidationParameters

{

ValidateIssuer = true,

ValidateAudience = true,

ValidateLifetime = true,

ValidateIssuerSigningKey = true,

ValidIssuer = configuration["Jwt:Issuer"],

ValidAudience = configuration["Jwt:Audience"],

IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]))

};

});

}

}

// Example: Creating a Authorization.cs class the file is kept in Extensions Folder in Project EntityFrameworkCoreGuideNET8.Business.UI

namespace EntityFrameworkCoreGuideNET8.Business.UI.Extensions;

public static class Authorization

{

public static void AddAdminAuthorization(this IServiceCollection services)

{

services.AddAuthorization(options =>

{

options.AddPolicy("AdminOnly", policy =>

{

policy.RequireRole("Admin");

});

});

}

}

使用 ASP.NET Core 和 EF Core,需要实现最佳实践,例如存储库模式和工作单元、处理并发和乐观锁定以及通过身份验证和授权保护数据访问。这些最佳实践使开发人员能够构建可扩展、安全且可维护的 API。

Entity Framework Core 的 C# 10 功能

利用 C# 10 中引入的新功能可以极大地增强我们使用 Entity Framework Core (EF Core) 开发的经验。通过利用这些功能,开发人员可以简化他们的代码,提高可读性并提高生产力。

C# 10 中最值得注意的功能之一就是记录类型的使用。记录类型提供了一种简洁而富有表现力的方式来定义不可变数据类型,使其成为需要实体表示的 EF Core 应用程序的理想选择。由于对实体类使用记录类型,开发人员可以减少样板代码并提高代码清晰度。

// Example: Using record types for entity classes

public record User

{

public int Id { get; init; }

public string FirstName { get; init; }

public string LastName { get; init; }

}

此外,C# 10 引入了许多模式匹配增强功能,这些功能对 EF Core 开发大有裨益。开发人员可以使用模式匹配增强功能简化复杂代码并提高可维护性。通过使用模式匹配增强功能,开发人员可以编写更具表现力和简洁的代码来处理条件逻辑。

在 C# 10 中,引入了可空引用类型。可空引用类型允许开发人员注释其代码以指示允许或不允许空值的位置。开发人员可以通过使用可空引用类型来降低 EF Core 应用程序中出现运行时错误的可能性,从而使其代码更加健壮并防止出现空引用异常。

通过利用 C# 10 中引入的最新功能(例如记录类型、模式匹配增强功能和可空引用类型),Web 开发人员可以改善 Entity Framework Core 开发体验,从而获得更高效、更强大且更易于维护的代码库。借助这些功能和 EF Core,开发人员可以轻松构建高质量、可扩展的应用程序。

Entity Framework Core 性能优化

Entity Framework Core (EF Core) 应用程序必须了解性能优化技术,以确保高效的数据库操作。通过优化数据库操作,开发人员可以显著增强其应用程序的性能和响应能力,从而提供更好的用户体验和更高的可扩展性。

为了优化查询执行,数据库索引有助于提供一种快速方法来定位数据库表中的特定行,从而加快查询执行速度。通过在经常查询的列上创建索引,开发人员可以减少从数据库检索数据所需的时间,从而提高查询性能。

通过优化查询,还可以显著提高查询的性能。通过精心设计查询,开发人员可以最大限度地减少从数据库检索的数据量并最大限度地利用索引。可以使用多种技术来提高查询性能,包括避免不必要的连接、仅选择必要的列以及使用 WHERE 子句过滤数据。

通过将经常访问的数据缓存在内存中,开发人员可以减少数据库查询的数量并提高应用程序的响应能力,这对于性能优化也至关重要。使用 Redis 等内存缓存框架或实施分布式缓存解决方案可以帮助最大限度地减少数据库负载并提高应用程序性能。

为了有效优化性能,开发人员还必须监控和分析性能指标,以确定瓶颈和需要改进的领域。开发人员可以使用 Entity Framework Profiler 或 SQL Server Management Studio 等工具来查明性能问题并采取纠正措施,这些工具可以深入了解查询执行时间、数据库负载和资源利用率。

// Example: Creating a DemoDbContext class the file is kept in DbContext Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data;

public class DemoDbContext: DbContext

{

public DemoDbContext(DbContextOptions options) : base(options)

{

}

public DbSet<User> Users { get; set; }

// Other DbSet properties for additional entities

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer("OurConnectionString");

}

// Example: Creating a database index in EF Core

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<User>()

.HasIndex(u => u.Email)

.IsUnique();

}

}

我们开发人员可以通过使用性能优化技术(如数据库索引、优化查询、实施缓存策略和监控性能指标)来提高其 EF Core 应用程序的性能。通过将这些技术与仔细的分析和调整相结合,可以实现显着的性能改进和更好的用户体验。

测试 Entity Framework Core 应用程序

测试对于 Entity Framework Core (EF Core) 应用程序的可靠性和可维护性至关重要。通过全面测试我们的代码库,您可以在开发生命周期的早期识别和解决潜在问题,从而降低生产环境中出现错误和错误的风险。

可以使用不同类型的测试方法来测试 EF Core 应用程序,例如单元测试、集成测试和模拟框架。单独测试单个组件和代码单元称为单元测试。相比之下,集成测试涉及确保不同的组件或模块能够顺利协同工作。

作为在 EF Core 应用程序中测试数据库交互的一种方式,开发人员经常使用模拟框架来模拟数据库行为,而无需实际访问数据库。您可以通过使用模拟框架创建模拟真实数据库对象行为的模拟对象来隔离我们的测试,而无需依赖外部依赖项。

设置内存数据库或使用模拟库也是测试 EF Core 应用程序的有用技术。使用内存数据库,您可以针对仅存在于内存中的临时数据库运行测试,从而为传统数据库系统提供轻量级且快速的替代方案。通过为数据库操作创建模拟对象,模拟库消除了在测试期间与物理数据库交互的需要。

通过实施单元测试、集成测试、模拟框架以及内存数据库或模拟库等测试策略,我们的 EF Core 应用程序的可靠性和可维护性可以得到极大提高。如果您投入时间和精力进行测试,我们的软件将发挥最佳性能。

//DbContextMocker.cs class the file is kept in Project EntityFrameworkCoreGuideNET8.Tests

using EntityFrameworkCoreGuideNET8.Infrastructure.Data;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Tests;

public static class DbContextMocker

{

public static DemoDbContext GetDemoDbContext(string dbName)

{

var options = new DbContextOptionsBuilder<DemoDbContext>()

.UseInMemoryDatabase(databaseName: dbName)

.Options;

var dbContext = new DemoDbContext(options);

// Seed your in-memory database with test data if needed

return dbContext;

}

}

//UserRepositoryTests.cs class the file is kept in Project EntityFrameworkCoreGuideNET8.Tests

using EntityFrameworkCoreGuideNET8.Infrastructure.Data.Repository;

namespace EntityFrameworkCoreGuideNET8.Tests;

public class UserRepositoryTests

{

// Example: Writing unit tests for EF Core repositories

Fact

public async Task GetUsers_ReturnsAllUsers()

{

// Arrange

var dbContext = DbContextMocker.GetDemoDbContext(nameof(GetUsers_ReturnsAllUsers));

var repository = new UserRepository(dbContext);

// Act

var users = await repository.GetAllActiveUsersAsync();

// Assert

Assert.Equal(3, users.Count);

}

}

Entity Framework Core 最佳实践

保持代码质量和一致性

使用 Entity Framework Core (EF Core) 时,保持代码质量和一致性对于确保应用程序的稳健性和可维护性至关重要。通过遵守推荐的最佳实践和惯例,开发人员可以简化开发、提高代码可读性并最大限度地减少潜在问题。让我们探索其中一些最佳实践。

// Example: Creating a DemoDbContext class the file is kept in DbContext Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data;

public class DemoDbContext: DbContext

{

public DemoDbContext(DbContextOptions options) : base(options)

{

}

public DbSet<User> Users { get; set; }

// Other DbSet properties for additional entities

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer("OurConnectionString");

}

// Example: Creating a database index in EF Core

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<User>()

.HasIndex(u => u.Email)

.IsUnique();

// Fluent API configurations

modelBuilder.Entity<User>()

.Property(e => e.Id)

.IsRequired();

}

}

using EntityFrameworkCoreGuideNET8.Infrastructure.Data;

using Microsoft.EntityFrameworkCore;

Console.WriteLine("Hello, from Ziggy Rafiq!");

using (var context = new DemoDbContext(new DbContextOptionsBuilder<DemoDbContext>()

.UseSqlServer("our_connection_string_here").Options))

{

// Use context to interact with the database

}

使用有意义的命名约定

为实体、属性和方法选择描述性名称,以增强代码的可读性和理解性。

// Example: Creating a User record the file is kept in Models Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using System.ComponentModel.DataAnnotations;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

public record User

{

Key

public Guid Id { get; init; }

public List<Order> Orders { get; init; } = new List<Order>();

Required

public string FirstName { get; init; } = string.Empty;

Required

public string LastName { get; init; } = string.Empty;

Required

public string Email { get; init; } = string.Empty;

Required

public string EmailConfirmed { get; init; } = string.Empty;

Required

public string Phone { get; init; } = string.Empty;

Required

public string PhoneConfirmed { get; init; } = string.Empty;

public bool IsActive { get; init; } = false;

Timestamp

public byte[]? RowVersion { get; set; }

}

保持 DbContext 精简且专注

避免用不必要的配置或依赖项来扰乱 DbContext 类。专注于定义实体及其关系。

// Example: Creating a DemoDbContext class the file is kept in DbContext Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data;

public class DemoDbContext: DbContext

{

public DemoDbContext(DbContextOptions options) : base(options)

{

}

public DbSet<User> Users { get; set; }

// Other DbSet properties for additional entities

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer("OurConnectionString");

}

}

使用数据注释或 Fluent API

一致地选择数据注释或 Fluent API 来配置实体和关系。对于更复杂的配置,最好使用 Fluent API。

// Example: Creating a User record the file is kept in Models Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using System.ComponentModel.DataAnnotations;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

public record User

{

Key

public Guid Id { get; init; }

public List<Order> Orders { get; init; } = new List<Order>();

Required

public string FirstName { get; init; } = string.Empty;

Required

public string LastName { get; init; } = string.Empty;

Required

public string Email { get; init; } = string.Empty;

Required

public string EmailConfirmed { get; init; } = string.Empty;

Required

public string Phone { get; init; } = string.Empty;

Required

public string PhoneConfirmed { get; init; } = string.Empty;

public bool IsActive { get; init; } = false;

Timestamp

public byte[]? RowVersion { get; set; }

}

// Example: Creating a UserRepository class the file is kept in Models Folder in Project EntityFrameworkCoreGuideNET8.Domain

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

public record Order

{

Key

public Guid Id { get; init; }

public Guid UserId { get; init; }

ForeignKey("UserId")

public required User User { get; init; }

Required

public string ProductName { get; init; }=string.Empty;

Required,Range(0, double.MaxValue, ErrorMessage = "Price must be a positive value.")

public decimal Price { get; init; }

Required

public DateTime OrderDate { get; init; }

}

使用时间戳处理并发

当多个用户同时更新同一个实体时,使用时间戳(例如,RowVersion)来处理并发冲突。

// Example: Creating a User record the file is kept in Models Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using System.ComponentModel.DataAnnotations;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

public record User

{

Key

public Guid Id { get; init; }

public List<Order> Orders { get; init; } = new List<Order>();

Required

public string FirstName { get; init; } = string.Empty;

Required

public string LastName { get; init; } = string.Empty;

Required

public string Email { get; init; } = string.Empty;

Required

public string EmailConfirmed { get; init; } = string.Empty;

Required

public string Phone { get; init; } = string.Empty;

Required

public string PhoneConfirmed { get; init; } = string.Empty;

public bool IsActive { get; init; } = false;

Timestamp

public byte[]? RowVersion { get; set; }

}

优化数据库交互

通过适当使用预先加载、显式加载或延迟加载来最大限度地减少数据库往返次数。通过在需要时预先加载相关实体来避免 N+1 查询问题。

// Eager loading example

var users = dbContext.Users.Include(u => u.Orders).ToList();

妥善处理异常

实现错误处理机制,以便妥善处理 EF Core 操作引发的异常。使用 try-catch 块捕获特定异常并向用户提供有意义的错误消息。

// Example: Creating a UserRepository class the file is kept in Repository Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.DTOs;

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Interfaces;

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data.Repository;

public class UserRepository : IUserRepository

{

private readonly DemoDbContext _dbContext;

private bool _disposed = false;

public UserRepository(DemoDbContext dbContext)

{

_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));

}

/// <summary>

/// Add or Updates the User

/// </summary>

/// <param name="user">User Model</param>

/// <returns></returns>

public async Task SaveAsync(User user)

{

try

{

_dbContext.Entry(user).State = user.Id == Guid.Empty ? EntityState.Added : EntityState.Modified;

await _dbContext.SaveChangesAsync();

}

catch (DbUpdateException ex)

{

Console.WriteLine("An error occurred while saving changes to the database: " + ex.Message);

}

}

protected virtual void Dispose(bool disposing)

{

if (_disposed)

return;

if (disposing)

{

_dbContext.Dispose();

}

_disposed = true;

}

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

}

通过遵循这些最佳实践和惯例,开发人员可以在使用 Entity Framework Core 时保持代码质量、一致性和可靠性。这些实践有助于在 .NET 生态系统中构建可扩展、可维护且高效的应用程序。

使用 DTO(数据传输对象)

ASP.NET Core 应用程序中使用 Entity Framework Core (EF Core) 时,利用数据传输对象 (DTO) 进行投影可带来许多好处,包括提高性能、减少数据传输和增强安全性。此外,避免在控制器中直接使用 DbSet 有助于保持关注点分离并促进更清晰、更易于维护的代码。让我们深入研究实现 DTO 和避免在控制器中直接使用 DbSet 的最佳实践:

实现投影的 DTO

创建针对特定用例定制的 DTO 类,以在我们的应用程序层之间传输数据。DTO 允许您根据客户端的需要精确地调整从 EF Core 查询返回的数据,而无需直接公开我们的域实体。

// DTOs.cs file in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Domain.DTOs;

public record UserDto(Guid Id, string FirstName, string LastName, string Email, string Phone, bool IsActive);

public record OrderDto(Guid Id, Guid UserId, string ProductName, decimal Price, DateTime OrderDate);

使用投影填充 DTO

从 EF Core 查询数据时,使用投影将查询结果直接映射到 DTO。此方法减少了通过网络传输的数据量,并通过仅获取所需字段来提高性能。

// Example: Creating a UserRepository class the file is kept in Repository Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.DTOs;

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Interfaces;

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Data.Repository;

public class UserRepository : IUserRepository

{

private readonly DemoDbContext _dbContext;

private bool _disposed = false;

public UserRepository(DemoDbContext dbContext)

{

_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));

}

/// <summary>

/// This example demonstrates the usage of UserDto for accessing the data.

/// </summary>

/// <returns>List of Users</returns>

public Task<List<UserDto>> GetUserDtosAsync() => _dbContext.Users

.Select(u => new UserDto(

u.Id,

u.FirstName,

u.LastName,

u.Email,

u.Phone,

u.IsActive

))

.ToListAsync();

protected virtual void Dispose(bool disposing)

{

if (_disposed)

return;

if (disposing)

{

_dbContext.Dispose();

}

_disposed = true;

}

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

}

避免在控制器中直接使用 DbSet

不要直接从控制器返回 DbSet,而是将数据投影到 DTO 中,以确保只向客户端公开必要的数据。这种方法有助于防止过度获取数据,并最大限度地降低与公开域实体相关的潜在安全风险。

ApiController

Route("api/users")

public class UserController : ControllerBase

{

private readonly MyDbContext _dbContext;

public UserController(MyDbContext dbContext)

{

_dbContext = dbContext;

}

HttpGet

public ActionResult<IEnumerable<UserDto>> GetUsers()

{

var userDtos = _dbContext.Users

.Select(u => new UserDto

{

UserId = u.UserId,

UserName = u.UserName,

// Map other properties as needed...

})

.ToList();

return Ok(userDtos);

}

}

通过利用 DTO 进行投影并避免在控制器中直接使用 DbSet,开发人员可以设计更高效、更安全且更易于维护的 ASP.NET Core 应用程序。这种方法有助于更好地分离关注点、提高性能并提高整体代码质量。

确保妥善处理并发冲突

确保妥善处理并发冲突、实现日志记录和错误处理以及定期更新 EF Core 及其依赖项是维护 ASP.NET Core 应用程序的可靠性、安全性和性能的关键实践。让我们详细探讨这些最佳实践:

妥善处理并发冲突

当多个用户尝试同时修改同一数据时,可能会发生并发冲突。EF Core 提供了检测和解决这些冲突的机制,例如使用时间戳或行版本控制。实施适当的并发控制策略来处理冲突并确保数据完整性。

// Example: Creating a User record the file is kept in Models Folder in Project EntityFrameworkCoreGuideNET8.Infrastructure.Data

using System.ComponentModel.DataAnnotations;

namespace EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Models;

public record User

{

Key

public Guid Id { get; init; }

public List<Order> Orders { get; init; } = new List<Order>();

Required

public string FirstName { get; init; } = string.Empty;

Required

public string LastName { get; init; } = string.Empty;

Required

public string Email { get; init; } = string.Empty;

Required

public string EmailConfirmed { get; init; } = string.Empty;

Required

public string Phone { get; init; } = string.Empty;

Required

public string PhoneConfirmed { get; init; } = string.Empty;

public bool IsActive { get; init; } = false;

Timestamp

public byte[]? RowVersion { get; set; }

}

实施日志记录和错误处理

日志记录和错误处理对于识别和诊断生产环境中的问题至关重要。使用 Serilog 或 NLog 等日志记录框架来记录应用程序事件、错误和警告。实施结构化日志记录以捕获相关信息以进行故障排除。

using EntityFrameworkCoreGuideNET8.Business.UI.Models;

using EntityFrameworkCoreGuideNET8.Infrastructure.Domain.Interfaces;

using Microsoft.AspNetCore.Mvc;

using System.Diagnostics;

namespace EntityFrameworkCoreGuideNET8.Business.UI.Controllers

{

public class HomeController : Controller

{

private readonly ILogger<HomeController> _logger;

private readonly IUserService _userService;

public HomeController(ILogger<HomeController> logger, IUserService userService)

{

_logger = logger;

_userService = userService;

}

public IActionResult Index()

{

return View();

}

public IActionResult Privacy()

{

return View();

}

HttpGet

public async Task<IActionResult> GetAllActiveUser()

{

try

{

var user = await _userService.GetAllActiveUsersAsync();

if (user == null)

{

return NotFound();

}

return Ok(user);

}

catch (Exception ex)

{

_logger.LogError(ex, "An error occurred while retrieving the user.");

return StatusCode(500, "An unexpected error occurred.");

}

}

ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)

public IActionResult Error()

{

return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });

}

}

}

定期更新 EF Core 和依赖项

EF Core 会定期发布更新,以推出新功能、增强功能和错误修复。及时了解最新的 EF Core 版本,并定期更新我们项目的依赖项以利用改进和安全补丁。

dotnet add package Microsoft.EntityFrameworkCore --version x.x.x

通过遵循这些最佳实践,开发人员可以增强其 ASP.NET Core 应用程序的可靠性、安全性和性能。妥善处理并发冲突、实现强大的日志记录和错误处理以及保持 EF Core 和依赖项更新是确保应用程序长期成功的关键步骤。

概括

作为现代 .NET 开发的基石,Entity Framework Core 提供了强大的数据访问解决方案。通过使用 C# 10 和 .NET 8 的最新功能,开发人员可以改善数据库交互、提高性能并提高生产力。通过阅读本综合指南,您将能够充分利用 Entity Framework Core。通过掌握这些概念、技术和最佳实践,您将确保我们的 .NET 应用程序的可扩展性、可靠性和可维护性。

相关推荐
ArabySide6 天前
【EF Core】 EF Core 批量操作的进化之路——从传统变更跟踪到无跟踪更新
数据库·.net·efcore
woflyoycm7 天前
EFcore8和Sql Server 2014冲突
sqlserver·asp.net·efcore·ef8·ef9
CSharp精选营22 天前
ASP.NET Core EFCore 属性配置与DbContext 详解
.net core·efcore·dbcontext
csdn_aspnet4 个月前
Asp.Net Core 8.0 使用 Serilog 按日志级别写入日志文件的两种方式
serilog·.net8.0
csdn_aspnet5 个月前
使用 .NET 6 或 .NET 8 上传大文件
.net6.0·.net8.0
tiankong12136 个月前
个人笔记:ROM数据库框架EFCore使用示例,运行通过,附源码
数据库·笔记·efcore
GISer_Qing6 个月前
ASP.NET Core8.0学习笔记(二十四)——EF Core级联插入与删除
.netcore·linq·efcore
万雅虎6 个月前
.NET9 EFcore支持早期MSSQL数据库 ROW_NUMBER()分页
sqlserver·efcore·net9
csdn_aspnet7 个月前
.NET 8 Web API 中的身份验证和授权
webapi·.net8.0