JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.63k stars 1.05k forks source link

When Query from db and return IEnumable, will execute 2 times for sql query #2247

Closed 1257960069 closed 2 months ago

1257960069 commented 2 months ago

Describe the bug A clear and concise description of what the bug is. image

To Reproduce Provide a small working example that shows the issue.

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem. image

Additional context

Add any other context about the problem here.
using System.Data.Common;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using CsvHelper;
using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

namespace WebApplication1.Services
{
    public class CsvService(DbConnection dbConnection) : ControllerBase
    {
        [HttpGet]
        public async Task DownloadCsv(string query, string fileName)
        {
            var response = Response;
            response.ContentType = "text/csv";
            response.Headers.Add("Content-Disposition", new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName
            }.ToString());

            var dataRecords = dbConnection.Query(query, buffered: false);

            using var writer = new StreamWriter(response.Body);
            using var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture);
            await csvWriter.WriteRecordsAsync(dataRecords);
        }
    }
}
JoshClose commented 2 months ago

Fixed in 32.0.2.

snaumenko-st commented 1 month ago

I think there is a bug with the implementation, as enumerators should always be disposed after use. They can contain SQL sessions and other resources.

JoshClose commented 1 month ago

Fixed in 32.0.3.