Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created January 15, 2025 00:43
Show Gist options
  • Save karenpayneoregon/5b30f019e45e5ab885273610abb18cb6 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/5b30f019e45e5ab885273610abb18cb6 to your computer and use it in GitHub Desktop.
ChatGPT generated method

For an experiment, I provided ChatGPT with a prompt and an SQL statement to generate a method to work with a modified version of the NorthWind database using Dapper. The code worked, but with two minor modifications to speed up the execution.

The prompt For C# using the following SQL-Server query and NuGet package Dapper create a method to return data.

internal class DataOperations
{
public static IEnumerable<Customer> GetCustomerDetails()
{
using IDbConnection connection = new SqlConnection(DataConnections.Instance.MainConnection);
var customerDictionary = new Dictionary<int, Customer>();
var customers = connection.Query<Customer, Contact, Country, ContactType, Customer>(
SqlStatements.CustomerWithContacts(),
(customer, contact, country, contactType) =>
{
if (!customerDictionary.TryGetValue(customer.CustomerIdentifier, out var existing))
{
existing = customer;
customerDictionary[customer.CustomerIdentifier] = existing;
}
existing.Contact = contact;
existing.Country = country;
existing.ContactType = contactType;
return existing;
},
splitOn: "ContactId,CountryIdentifier,ContactTypeIdentifier");
return customers;
}
}
internal class SqlStatements
{
public static string CustomerWithContacts() =>
"""
SELECT CU.CustomerIdentifier,
CU.CompanyName,
CU.ContactId,
CU.Street,
CU.City,
CU.PostalCode,
CU.CountryIdentifier,
CU.Phone,
CU.Fax,
CU.Region,
CU.ModifiedDate,
CU.ContactTypeIdentifier,
C.ContactId,
C.FirstName,
C.LastName,
C.ContactTypeIdentifier,
CO.CountryIdentifier,
CO.Name,
CT.ContactTypeIdentifier,
CT.ContactTitle
FROM dbo.Customers AS CU
INNER JOIN dbo.Contacts AS C
ON CU.ContactId = C.ContactId
INNER JOIN dbo.Countries AS CO
ON CU.CountryIdentifier = CO.CountryIdentifier
INNER JOIN dbo.ContactType AS CT
ON CU.ContactTypeIdentifier = CT.ContactTypeIdentifier
AND C.ContactTypeIdentifier = CT.ContactTypeIdentifier;
""";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment