SoFunction
Updated on 2025-04-14

Detailed steps to use Cursor for C# programming

1. Description of the depth of environment configuration

1. .NET SDK version management

  • Recommended installation:use.NET SDK 8.0 LTS
  • Multi-version switching
# View installed versiondotnet --list-sdks

# Set the default version globallydotnet new globaljson --sdk-version 8.0.301
  • Cursor Integration: Specify the SDK path in the settings (File > Preferences > Settings > .NET SDK Path

2. C# extension configuration

  • Must-install plug-ins
    • C# Dev Kit(Official Intelligent Sensing)
    • NuGet Package Manager(Dependence management)
    • EF Core Power Tools(Database reverse engineering)
  • Debugging configuration:exist.vscode/Added in:
{
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      "program": "${workspaceFolder}/bin/Debug/net8.0/",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "serverReadyAction": {
        "action": "openExternally",
        "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
      }
    }
  ]
}

2. Advanced cases: Building a complete CRUD application

Case objective: Develop a library management API that includes JWT certification and Swagger documentation

Step 1: Generate the Infrastructure

  • Enter the command:
Create a Core Web APIproject,Includes the following functions:
- useEntity Framework Core + SQLite
- IncludeBookModel(Id:int, Title:string, Author:string, ISBN:string)
- IncludeBooksControllerofCRUDEndpoint
- EnableSwagger
  • AI-generatedKey Code:
<AppDbContext>(options => 
    (("Default")));

();
();

Step 2: Add JWT Authentication

  • Enter in the dialog window:
Add to the current projectJWT BearerCertification,Require:
- generateUserModel(Username, PasswordHash)
- Add toAuthControllerof/loginEndpoint
- existSwagger中显示Certification按钮
  • AI-generatedExample:
public class JwtService
{
    private readonly IConfiguration _config;
    
    public JwtService(IConfiguration config) => _config = config;

    public string GenerateToken(User user)
    {
        var key = new SymmetricSecurityKey(
            Encoding.(_config["Jwt:Key"]!));
        
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        
        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Audience"],
            claims: new[] { new Claim(, ) },
            expires: (1),
            signingCredentials: creds);
        
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

Step 3: Data Verification Enhancement

  • SelectBookModel class, enter:
forBookModel data annotation verification:
- Titlelength1-100character
- ISBNMust comply with regular expressions^\d{3}-\d{10}$
- Author不能for空
  • Generate results:
public class Book
{
    public int Id { get; set; }
    
    [Required]
    [StringLength(100, MinimumLength = 1)]
    public string Title { get; set; }
    
    [Required]
    [RegularExpression(@"^\d{3}-\d{10}$", 
        ErrorMessage = "ISBN format should be XXX-XXXXXXXXXXX")]
    public string ISBN { get; set; }
    
    [Required]
    public string Author { get; set; }
}

3. Deep integration of debugging and testing

1. AI-assisted debugging

  • Error diagnosis: Copy the compilation error message to the dialog window and enterExplain this error and provide a fix
CS1061: 'AppDbContext' does not contain a definition for 'Books'...
  • AI response example:
This error indicatesDbContextLackDbSet&lt;Book&gt;property。Solution:
1. existAppDbContextAdded in:
   public DbSet&lt;Book&gt; Books { get; set; }
2. Execute the migration command:
   dotnet ef migrations add AddBooksTable
   dotnet ef database update

2. Unit test generation

  • New,enter:
usexUnitforBookServiceWrite tests:
- testGetAllBooks返回空列表当数据库for空
- testCreateBookReturn to correctISBN
  • AI generation example:
public class BookServiceTests : IDisposable
{
    private readonly AppDbContext _context;

    public BookServiceTests()
    {
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlite("DataSource=:memory:")
            .Options;
        
        _context = new AppDbContext(options);
        _context.();
        _context.();
    }

    [Fact]
    public async Task GetAllBooks_ReturnsEmptyList_WhenNoBooks()
    {
        var service = new BookService(_context);
        var result = await ();
        (result);
    }
}

4. Enterprise-level development specifications

1. Architectural Mode Boot

Example input command:

useClean ArchitectureRefactor the current project,Include:
- Applicationlayer(MediatR + AutoMapper)
- Infrastructurelayer(EF Coreaccomplish)
- APIlayer(Minimal APIEndpoint)

The AI ​​will generate:

// Application/Books/Queries/
public record GetAllBooksQuery : IRequest<List<BookDto>>;

public class GetAllBooksHandler : IRequestHandler<GetAllBooksQuery, List<BookDto>>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public GetAllBooksHandler(IApplicationDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<List<BookDto>> Handle(GetAllBooksQuery request, CancellationToken ct)
    {
        return _mapper.Map<List<BookDto>>(
            await _context.(ct));
    }
}

2. Performance optimization guidance

enter:

Optimize the data access layer:
- forGetBookByIdAdd toAsNoTracking
- Use in queryProjectToAutomatic mappingDTO
- Add to内存缓存策略

AI generation:

public async Task<BookDto> GetBookById(int id)
{
    return await _memoryCache.GetOrCreateAsync($"book_{id}", async entry =>
    {
         = (5);
        return await _context.Books
            .AsNoTracking()
            .Where(b =>  == id)
            .ProjectTo<BookDto>(_mapper.ConfigurationProvider)
            .FirstOrDefaultAsync();
    });
}

5. Things to note about enterprise-level projects (supplementary)

  • Safety Specifications

    • use[Authorize(Policy = "RequireAdmin")]Perform fine-grained permission control
    • existIsolate sensitive information throughdotnet user-secretsmanage
dotnet user-secrets init
dotnet user-secrets set "Jwt:Key" "YourSecureKeyHere"
  • CI/CD integration
    • Enter in the dialog windowGenerate GitHub Actions configuration for building and deploying to Azure, AI will generate:
name: .NET Core CI

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: 8.
    - name: Restore dependencies
      run: dotnet restore
    - name: Build
      run: dotnet build --configuration Release --no-restore
  • Code quality control
    • enterAdd SonarQube static analysis configuration,generate:
<PropertyGroup>
  <SonarQubeExclude>**/Migrations/**</SonarQubeExclude>
  <SonarQubeTestProject>false</SonarQubeTestProject>
</PropertyGroup>

6. Cursor advanced function mining

  • Code visualization

    • enterGenerate UML class diagram of Book class, AI outputs PlantUML code:
@startuml
class Book {
  +int Id
  +string Title
  +string Author
  +string ISBN
}
@enduml
    • InstallPlantUML extensionDirect preview
  • SQL Conversion

    • enterConvert the following LINQ to native SQL
(b =>  == ". Tolkien").OrderBy(b => )
  • AI output:
SELECT * FROM Books 
WHERE Author = '. Tolkien' 
ORDER BY Title ASC
  • Multimodal development
    • Upload interface sketch, enterGenerate WPF XAML code from this UI, AI generation:
<Window>
  <Grid>
    <DataGrid ItemsSource="{Binding Books}">
      <>
        <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
      </>
    </DataGrid>
  </Grid>
</Window>

The above supplementary content covers the complete life cycle of enterprise-level development. Recommended when using it:

  • Generate code step by step by step by module
  • Manual review of key business logic
  • Establish a project-levelCommon prompt word templates for file records

The above is the detailed steps for using Cursor for C# programming. For more information about Cursor for C# programming, please pay attention to my other related articles!