moai-lang-csharp

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

C# 12 / .NET 8 Development Specialist

C# 12 / .NET 8 开发专家

Modern C# development with ASP.NET Core, Entity Framework Core, Blazor, and enterprise patterns.
基于 ASP.NET Core、Entity Framework Core、Blazor 及企业级设计模式的现代 C# 开发指南。

Quick Reference

快速参考

Auto-Triggers:
.cs
,
.csproj
,
.sln
files, C# projects, .NET solutions, ASP.NET Core applications
Core Stack:
  • C# 12: Primary constructors, collection expressions, alias any type, default lambda parameters
  • .NET 8: Minimal APIs, Native AOT, improved performance, WebSockets
  • ASP.NET Core 8: Controllers, Endpoints, Middleware, Authentication
  • Entity Framework Core 8: DbContext, migrations, LINQ, query optimization
  • Blazor: Server/WASM components, InteractiveServer, InteractiveWebAssembly
  • Testing: xUnit, NUnit, FluentAssertions, Moq
Quick Commands:
To create a new .NET 8 Web API project, run dotnet new webapi with -n flag for project name and --framework net8.0.
To create a Blazor Web App, run dotnet new blazor with -n flag for project name and --interactivity Auto.
To add Entity Framework Core, run dotnet add package Microsoft.EntityFrameworkCore.SqlServer followed by Microsoft.EntityFrameworkCore.Design.
To add FluentValidation and MediatR, run dotnet add package FluentValidation.AspNetCore and dotnet add package MediatR.

自动触发场景:
.cs
.csproj
.sln
文件,C# 项目,.NET 解决方案,ASP.NET Core 应用程序
核心技术栈:
  • C# 12:主构造函数、集合表达式、任意类型别名、默认 Lambda 参数
  • .NET 8:Minimal APIs、Native AOT、性能优化、WebSockets
  • ASP.NET Core 8:控制器、端点、中间件、身份验证
  • Entity Framework Core 8:DbContext、迁移、LINQ、查询优化
  • Blazor:Server/WASM 组件、InteractiveServer、InteractiveWebAssembly
  • 测试:xUnit、NUnit、FluentAssertions、Moq
快速命令:
创建新的 .NET 8 Web API 项目:运行
dotnet new webapi
,使用
-n
参数指定项目名称,
--framework net8.0
指定框架版本。
创建 Blazor Web 应用:运行
dotnet new blazor
,使用
-n
参数指定项目名称,
--interactivity Auto
设置交互模式为自动。
添加 Entity Framework Core:先运行
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
,再运行
dotnet add package Microsoft.EntityFrameworkCore.Design
添加 FluentValidation 和 MediatR:运行
dotnet add package FluentValidation.AspNetCore
dotnet add package MediatR

Module Index

模块索引

This skill uses progressive disclosure with specialized modules for deep coverage:
本技能采用渐进式展示,通过专业模块提供深度内容:

Language Features

语言特性

  • C# 12 Features - Primary constructors, collection expressions, type aliases, default lambdas
  • C# 12 特性 - 主构造函数、集合表达式、类型别名、默认 Lambda

Web Development

Web 开发

  • ASP.NET Core 8 - Minimal API, Controllers, Middleware, Authentication
  • Blazor Components - Server, WASM, InteractiveServer, Components
  • ASP.NET Core 8 - Minimal API、控制器、中间件、身份验证
  • Blazor 组件 - Server、WASM、InteractiveServer、组件

Data Access

数据访问

  • Entity Framework Core 8 - DbContext, Repository pattern, Migrations, Query optimization
  • Entity Framework Core 8 - DbContext、仓储模式、迁移、查询优化

Architecture Patterns

架构模式

  • CQRS and Validation - MediatR CQRS, FluentValidation, Handler patterns
  • CQRS 与验证 - MediatR CQRS、FluentValidation、处理程序模式

Reference Materials

参考资料

  • API Reference - Complete API reference, Context7 library mappings
  • Code Examples - Production-ready examples, testing templates

  • API 参考 - 完整 API 参考、Context7 库映射
  • 代码示例 - 生产就绪示例、测试模板

Implementation Quick Start

快速上手实现

Project Structure (Clean Architecture)

项目结构(整洁架构)

Organize projects in a src folder with four main projects. MyApp.Api contains the ASP.NET Core Web API layer with Controllers folder for API Controllers, Endpoints folder for Minimal API endpoints, and Program.cs as the application entry point. MyApp.Application contains business logic including Commands folder for CQRS Commands, Queries folder for CQRS Queries, and Validators folder for FluentValidation. MyApp.Domain contains domain entities including Entities folder for domain models and Interfaces folder for repository interfaces. MyApp.Infrastructure contains data access including Data folder for DbContext and Repositories folder for repository implementations.
将项目组织在
src
文件夹中,包含四个主项目:
  • MyApp.Api:ASP.NET Core Web API 层,包含
    Controllers
    文件夹(API 控制器)、
    Endpoints
    文件夹(Minimal API 端点),以及应用入口文件
    Program.cs
  • MyApp.Application:业务逻辑层,包含
    Commands
    文件夹(CQRS 命令)、
    Queries
    文件夹(CQRS 查询)和
    Validators
    文件夹(FluentValidation 验证器)。
  • MyApp.Domain:领域实体层,包含
    Entities
    文件夹(领域模型)和
    Interfaces
    文件夹(仓储接口)。
  • MyApp.Infrastructure:数据访问层,包含
    Data
    文件夹(DbContext)和
    Repositories
    文件夹(仓储实现)。

Essential Patterns

核心设计模式

Primary Constructor with DI: Define a public class UserService with constructor parameters for IUserRepository and ILogger of UserService. Create async methods like GetByIdAsync that take Guid id, log information using the logger with structured logging for UserId, and return the result from repository.FindByIdAsync.
Minimal API Endpoint: Use app.MapGet with route pattern like "/api/users/{id:guid}" and an async lambda taking Guid id and IUserService. Call the service method, check for null result, and return Results.Ok for found entities or Results.NotFound otherwise. Chain WithName for route naming and WithOpenApi for OpenAPI documentation.
Entity Configuration: Create a class implementing IEntityTypeConfiguration of your entity type. In the Configure method taking EntityTypeBuilder, call HasKey to set the primary key, use Property to configure fields with HasMaxLength and IsRequired, and use HasIndex with IsUnique for unique constraints.

依赖注入的主构造函数:定义一个公共类
UserService
,构造函数参数为
IUserRepository
ILogger<UserService>
。创建异步方法如
GetByIdAsync
,接收
Guid id
参数,使用记录器输出包含
UserId
的结构化日志信息,返回
repository.FindByIdAsync
的结果。
Minimal API 端点:使用
app.MapGet
,路由模式如
"/api/users/{id:guid}"
,异步 lambda 表达式接收
Guid id
IUserService
。调用服务方法,检查结果是否为空,找到实体则返回
Results.Ok
,否则返回
Results.NotFound
。链式调用
WithName
设置路由名称,
WithOpenApi
生成 OpenAPI 文档。
实体配置:创建实现
IEntityTypeConfiguration<你的实体类型>
的类。在
Configure
方法(接收
EntityTypeBuilder
)中,调用
HasKey
设置主键,使用
Property
配置字段的
HasMaxLength
IsRequired
属性,使用
HasIndex
并设置
IsUnique
来添加唯一约束。

Context7 Integration

Context7 集成

For latest documentation, use Context7 MCP tools.
For ASP.NET Core documentation, first resolve the library ID using mcp__context7__resolve-library-id with "aspnetcore", then fetch docs using mcp__context7__get-library-docs with the resolved library ID and topic like "minimal-apis middleware".
For Entity Framework Core documentation, resolve with "efcore" and fetch with topics like "dbcontext migrations".
For .NET Runtime documentation, resolve with "dotnet runtime" and fetch with topics like "collections threading".

如需最新文档,请使用 Context7 MCP 工具。
获取 ASP.NET Core 文档:首先使用
mcp__context7__resolve-library-id
工具,传入参数 "aspnetcore" 解析库 ID,然后使用
mcp__context7__get-library-docs
工具,传入解析后的库 ID 和主题(如 "minimal-apis middleware")获取文档。
获取 Entity Framework Core 文档:使用 "efcore" 解析库 ID,传入主题如 "dbcontext migrations" 获取文档。
获取 .NET Runtime 文档:使用 "dotnet runtime" 解析库 ID,传入主题如 "collections threading" 获取文档。

Quick Troubleshooting

快速故障排查

Build and Runtime: Run dotnet build with --verbosity detailed for detailed output. Run dotnet run with --launch-profile https for HTTPS profile. Run dotnet ef database update to apply EF migrations. Run dotnet ef migrations add with migration name to create new migrations.
Common Patterns:
For null reference handling, use ArgumentNullException.ThrowIfNull with the variable and nameof expression after fetching from context.
For async enumerable streaming, create async methods returning IAsyncEnumerable of your type. Add EnumeratorCancellation attribute to the CancellationToken parameter. Use await foreach with AsAsyncEnumerable and WithCancellation to iterate, yielding each item.

构建与运行时:运行
dotnet build --verbosity detailed
获取详细输出;运行
dotnet run --launch-profile https
使用 HTTPS 配置文件启动;运行
dotnet ef database update
应用 EF 迁移;运行
dotnet ef migrations add <迁移名称>
创建新迁移。
常见问题处理模式:
空引用处理:从上下文获取数据后,使用
ArgumentNullException.ThrowIfNull(变量, nameof(变量))
进行空值检查。
异步可枚举流:创建返回
IAsyncEnumerable<你的类型>
的异步方法,为
CancellationToken
参数添加
EnumeratorCancellation
属性。使用
await foreach
结合
AsAsyncEnumerable()
WithCancellation()
进行迭代,逐个返回项。

Works Well With

协同技能

  • moai-domain-backend
    - API design, database integration patterns
  • moai-platform-deploy
    - Azure, Docker, Kubernetes deployment
  • moai-workflow-testing
    - Testing strategies and patterns
  • moai-foundation-quality
    - Code quality standards
  • moai-essentials-debug
    - Debugging .NET applications
  • moai-domain-backend
    - API 设计、数据库集成模式
  • moai-platform-deploy
    - Azure、Docker、Kubernetes 部署
  • moai-workflow-testing
    - 测试策略与模式
  • moai-foundation-quality
    - 代码质量标准
  • moai-essentials-debug
    - .NET 应用调试",