During a recent mission for a corporate client, I was asked to build a Proof of Concept (POC) for a Text-to-SQL Agent: allowing business analysts to query internal financial and operational databases using natural language. Think of questions like: "Give me the top 5 clients by total invoiced amount this year" or "How many invoices are currently in 'Paid' status?"
While building Text-to-SQL with public commercial LLM APIs (such as OpenAI or Anthropic) is simple, enterprise constraints quickly appeared: sending internal financial schemas to external public APIs was strictly forbidden for compliance and GDPR reasons.
Now, you might ask: why not use enterprise private AI platforms like Microsoft Azure AI Foundry (formerly Azure OpenAI Service) or Amazon Bedrock? These managed platforms guarantee data privacy, private networking, and tenant isolation within your cloud environment. However, in my client's context, no dedicated enterprise AI platform had been set up yet. Going through security validations, network setup, and budget approval for Azure AI Foundry or AWS Bedrock can take several months in a large organization.
Since the business team wanted a fast, concrete Proof of Concept without waiting months for cloud governance approvals, I chose a 100% local, self-hosted approach: running the AI model directly inside the existing .NET application, with zero external dependencies and zero extra cloud costs.
In this article, I will explain how I built this by combining Entity Framework Core metadata with local model execution using LLamaSharp in .NET 10, and how using the client's existing Azure App Service P3v3 instances allowed me to run it for free.
Architecture Overview: The V1 One-Shot Pipeline
Before diving into the code, here is the end-to-end execution flow of the V1 pipeline. Every user question goes through a single, linear pass:
The Infrastructure Opportunity: Unused RAM on Azure P3v3
When developers think about running LLMs locally, the first reaction is usually: "We don't have expensive GPU servers in our cloud budget."
However, when I checked the production environment, the backend APIs were already running on Azure App Service Plans (P3v3 tier). A P3v3 instance provides:
- 8 vCPUs (Intel Xeon / AMD EPYC processors)
- 32 GB of physical RAM
While the web APIs used CPU during peak hours, more than 20 GB of RAM was completely unused! Thanks to model quantization (such as the standard 4-bit GGUF Q4_K_M format), specialized coding models like Qwen2.5-Coder-7B or smaller models like Gemma-2-2B keep very high accuracy on SQL tasks while using only 1.5 GB to 5 GB of RAM.
Instead of renting dedicated GPU virtual machines or paying per-token API bills, I embedded the model directly inside the ASP.NET Core process using CPU inference. It runs on servers that are already paid for, ensures that no data ever leaves the server, and removes external network calls.
The Secret Weapon: EF Core as an AI Metamodel
Most Text-to-SQL tutorials tell you to export raw CREATE TABLE SQL scripts or query system tables (sys.tables, sys.columns).
This creates large, noisy prompts full of technical database details, without any business explanation.
If your application already uses Entity Framework Core, you already have everything you need. Your DbContext contains:
- Clear table and property names
- Business descriptions configured via
.HasComment(...) - Primary and Foreign Key relationships between entities
- C# Enums and their exact numeric values
Extracting Rich Metadata via IDesignTimeModel
In EF Core 8, 9, and 10, the default runtime model does not keep all relational comments in memory to save resources.
To read table comments and detailed schema metadata at runtime, I request the IDesignTimeModel service from the DbContext:
public class EfCoreSchemaGenerator : IEfCoreSchemaGenerator
{
private readonly AppDbContext _dbContext;
public EfCoreSchemaGenerator(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public string GetSchemaForLlm()
{
var sb = new StringBuilder();
// Access full metadata including relational comments
var model = _dbContext.GetService<IDesignTimeModel>().Model;
foreach (var entityType in model.GetEntityTypes())
{
var tableName = entityType.GetTableName();
if (string.IsNullOrEmpty(tableName)) continue;
sb.AppendLine($"Table: {tableName}");
var comment = entityType.GetComment();
if (!string.IsNullOrWhiteSpace(comment))
{
sb.AppendLine($"Description: {comment}");
}
sb.AppendLine("Columns:");
foreach (var property in entityType.GetProperties())
{
var colName = property.GetColumnName();
var colType = property.GetColumnType() ?? property.ClrType.Name;
var flags = new List<string>();
if (property.IsPrimaryKey()) flags.Add("PK");
if (property.IsForeignKey()) flags.Add("FK");
if (!property.IsNullable) flags.Add("NOT NULL");
var desc = property.GetComment();
var descStr = !string.IsNullOrWhiteSpace(desc) ? $" - {desc}" : "";
var flagStr = flags.Count > 0 ? $" [{string.Join("] [", flags)}]" : "";
sb.AppendLine($" - {colName} ({colType}){flagStr}{descStr}");
}
}
return sb.ToString();
}
}
Handling C# Enums Automatically
One of the most common mistakes in Text-to-SQL happens with numeric status columns.
If the user asks: "Find all paid invoices", how can the model know if Status is stored as 1, 2, or 'PAID'?
By checking the C# type of each property when building the schema, I automatically list all Enum integer values in the prompt:
var isEnum = property.ClrType.IsEnum ||
(Nullable.GetUnderlyingType(property.ClrType)?.IsEnum == true);
if (isEnum)
{
var enumType = property.ClrType.IsEnum
? property.ClrType
: Nullable.GetUnderlyingType(property.ClrType)!;
var values = Enum.GetValues(enumType)
.Cast<object>()
.Select(v => $"{Convert.ToInt32(v)} = {v}");
sb.AppendLine($"Enum Values: {property.GetColumnName()}: {string.Join(", ", values)}");
}
The resulting schema sent to the LLM is short and very clear:
Table: Invoices
Description: Invoices issued to corporate clients
Columns:
- Id (INTEGER) [PK]
- CustomerId (INTEGER) [FK] [NOT NULL] - Foreign key pointing to Customers.Id
- TotalAmountTTC (TEXT) [NOT NULL] - Total amount including taxes in EUR
- Status (INTEGER) [NOT NULL] - Payment status
Enum Values:
- Status: 0 = Draft, 1 = Pending, 2 = Paid, 3 = Overdue, 4 = Cancelled
Relationships:
- CustomerId -> Customers.Id
In-Process Local Inference with LLamaSharp
LLamaSharp is a great open-source library that provides C# bindings directly over llama.cpp.
You don't need Python, Docker, or an external service like Ollama. Everything runs directly inside your .NET process.
Dependency Injection Architecture
Loading a GGUF model into RAM takes a few seconds. I registered a Singleton service so the model weights are loaded only once when the application starts:
// Program.cs (.NET 10)
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite("Data Source=app.db"));
// Singleton: Keeps model weights in RAM across requests
builder.Services.AddSingleton<ILlmModelManager, LlmModelManager>();
// Scoped services for each HTTP request
builder.Services.AddScoped<IEfCoreSchemaGenerator, EfCoreSchemaGenerator>();
builder.Services.AddScoped<ISqlExecutor, SqlExecutor>();
builder.Services.AddScoped<ILlmChatService, LlmChatService>();
One-Shot SQL Generation
In this V1 pipeline, SQL generation is done in a single pass (One-Shot).
I use BatchedExecutor with special: true (so llama.cpp properly recognizes ChatML tags like <|im_start|> and <|im_end|>) and a deterministic GreedySamplingPipeline (temperature 0.0):
public async Task<string> GenerateSqlAsync(string question, CancellationToken ct = default)
{
var schema = _schemaGenerator.GetSchemaForLlm();
var systemPrompt = PromptConstants.GetV1SystemPrompt(schema);
var prompt = $"<|im_start|>system\n{systemPrompt}<|im_end|>\n" +
$"<|im_start|>user\nQuestion: {question}\n" +
$"Write the SQLite SELECT query to answer this question:<|im_end|>\n" +
$"<|im_start|>assistant\n";
using var executor = new BatchedExecutor(_modelManager.Weights!, _modelManager.ModelParameters!);
using var conversation = executor.Create();
// special: true ensures ChatML control tokens are parsed properly
var tokens = executor.Context.Tokenize(prompt, addBos: true, special: true);
conversation.Prompt(tokens);
using var sampler = new GreedySamplingPipeline();
var decoder = new StreamingTokenDecoder(executor.Context);
var sb = new StringBuilder();
for (var i = 0; i < 300; i++)
{
if (await executor.InferAsync(ct) != DecodeResult.Ok) break;
var token = sampler.Sample(executor.Context.NativeHandle, conversation.GetSampleIndex());
if (token == _modelManager.Weights!.Tokens.EOS) break;
decoder.Add(token);
sb.Append(decoder.Read());
conversation.Prompt(token);
}
return CleanSqlOutput(sb.ToString());
}
Safe Dynamic Execution with Dapper
Running SQL queries generated by an AI model requires strict security checks. Even on a read-only database, you should never trust raw LLM output blindly.
My execution service applies three safety rules:
- Read-only check: Queries must start with
SELECTorWITH. - Blocked keywords: A regular expression blocks any query containing
INSERT,UPDATE,DELETE,DROP,ALTER,TRUNCATE, orEXEC. - Dynamic result mapping: Dapper runs the query and returns
IEnumerable<IDictionary<string, object>>, which can be serialized directly to JSON without needing fixed C# classes.
public async Task<SqlExecutionResult> ExecuteSelectQueryAsync(string sqlQuery)
{
var trimmed = sqlQuery.Trim();
if (!trimmed.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase) &&
!trimmed.StartsWith("WITH", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Only SELECT queries are authorized.");
}
if (DangerousRegex.IsMatch(trimmed))
{
throw new InvalidOperationException("Destructive SQL keywords detected.");
}
var connection = _dbContext.Database.GetDbConnection();
var results = await connection.QueryAsync(trimmed);
return new SqlExecutionResult(results.Cast<IDictionary<string, object>>());
}
Open-Source Showcase: Try It Locally
To share this architecture, I published a complete repository on GitHub that you can clone and run locally in a few minutes, with no cloud account required:
- Backend: .NET 10 Web API with SQLite and Bogus (generating 60 customers and 350 invoices at startup).
- Frontend: A clean React 19 + TypeScript UI with sample questions, data tables, and SQL inspection.
- Model Setup Script: A
download-model.ps1script to download Qwen2.5-Coder directly from Hugging Face.
👉 View Source Code on GitHub (yfrouin/TextToSql-EfCore-LocalLlm)
Key Takeaways & Next Steps
This first version showed my client that private, internal AI assistants can run today on existing enterprise servers:
- Zero extra cloud costs: By using the available RAM on the existing Azure P3v3 App Service plans, there was no need to rent dedicated GPU machines.
- Full data privacy: Database schemas and queries stay inside the .NET process and never leave the company network.
- EF Core as an AI accelerator: Reading the EF Core metadata model gives the LLM the exact business context it needs to write SQL queries.
Update — V2 is now available! While this V1 One-Shot pipeline works well on standard queries, what happens when the LLM uses a MySQL function like CURDATE() or SUBSTRING_INDEX() that doesn't exist in SQLite?
In Text-to-SQL in .NET 10 (V2): Self-Healing Workflow with Microsoft Agent Framework, I upgrade this project to a two-agent workflow that discovers table schemas on demand and automatically fixes SQL errors at runtime!