How to stop Cursor forgetting your database schema (and your project rules)
Ask Cursor for a query against a table it touched yesterday and it may still guess the column name, invent a navigation property, or write a migration for a column that already exists. It looks like forgetting. It's actually something simpler: the agent never had your schema in the first place, and every new chat starts empty. This guide shows how to put an accurate, compact version of your EF Core schema where the agent will read it, keep it from going stale, and make your project rules stick at the same time.
Why Cursor gets your schema wrong
Language models don't retain memory between sessions; Cursor's own docs say so plainly, and that's why rules exist. Within a session, the agent only knows what it has read. On an EF Core codebase, the schema is spread across places it rarely reads together:
- Entity classes give property names, which are not necessarily column names.
- Fluent configuration (
IEntityTypeConfiguration<T>,OnModelCreating) renames tables and columns, sets keys, owned types, value conversions and query filters. - Conventions decide everything nobody configured explicitly, and they're invisible in the code.
- Migrations record how the schema got here, across dozens of files the agent has no reason to open.
Semantic search retrieves a slice of that, usually the entity class, and the model fills in the rest from the statistical average of every EF Core sample it was trained on. That's where CustomerId becomes customer_id, or an Orders collection appears on an entity that only has a foreign key. The cure is not a bigger model. It's giving the agent a single, accurate, compact source of truth, and telling it when to read it.
EF Core already writes a source of truth: the model snapshot
If you use migrations, you have a file that describes the current model as EF Core sees it: Migrations/<YourContext>ModelSnapshot.cs. Every table, column, type, key, index and relationship is there, with the real column names after configuration and conventions have been applied. It's regenerated by dotnet ef migrations add, so it's never hand-maintained.
Two problems: it's long (thousands of lines on a mature model), and it's C# builder code rather than something you'd want to scan quickly. It's a good reference for the agent to open deliberately, not something to paste into every prompt.
Generate a compact schema digest the agent can read
The most readable digest is the SQL your model would create. EF Core's tools generate it from the DbContext directly, bypassing migrations:
dotnet ef dbcontext script \
--project src/Infrastructure \
--startup-project src/Api \
--output docs/schema/schema.sql
Commit docs/schema/schema.sql. It's plain CREATE TABLE statements with real names, types, nullability, keys, indexes and foreign keys: exactly what a model needs to write a correct query or migration, in a fraction of the snapshot's size. For database-first projects, the database is the truth instead: regenerate entities with dotnet ef dbcontext scaffold and script the schema from the database with your usual tooling. Either way, the point is one committed file that describes the schema as it is now.
Keep the digest honest with a drift test
A digest that goes stale is worse than none, because the agent will trust it. Make CI enforce it. Database.GenerateCreateScript() produces the same SQL from code, and it only needs a relational provider configured; it never opens a connection:
using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore;
using Xunit;
public class SchemaDigestTests
{
[Fact]
public void Committed_schema_digest_matches_the_current_model()
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer("Server=.;Database=SchemaDigestOnly") // model only, no connection opened
.Options;
using var db = new AppDbContext(options);
var current = db.Database.GenerateCreateScript().ReplaceLineEndings("\n");
var path = Path.Combine(RepoRoot(), "docs", "schema", "schema.sql");
if (Environment.GetEnvironmentVariable("UPDATE_SCHEMA_DIGEST") == "1")
{
File.WriteAllText(path, current);
return;
}
var committed = File.ReadAllText(path).ReplaceLineEndings("\n");
Assert.True(committed == current,
"docs/schema/schema.sql is stale. Re-run with UPDATE_SCHEMA_DIGEST=1 and commit it.");
}
private static string RepoRoot([CallerFilePath] string thisFile = "") =>
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(thisFile)!, "..", ".."));
}
Swap UseSqlServer for UseNpgsql or your provider, and adjust RepoRoot() to your test project's depth. If you generate the committed file with the test itself (UPDATE_SCHEMA_DIGEST=1 dotnet test --filter SchemaDigest) rather than the CLI, the two can never disagree on formatting. Now the digest is guaranteed current, and "update the schema digest" becomes part of every migration the agent writes.
A schema rule that loads only for data-access work
Next, tell Cursor when to read the digest. A project rule in .cursor/rules/ with globs is attached automatically when a matching file is in context, so it costs nothing on API-layer or UI prompts:
---
description: EF Core schema source of truth for queries, entities and migrations
globs: src/Infrastructure/**/*.cs, **/Migrations/*.cs
alwaysApply: false
---
# Database schema
- Before writing a query, entity change or migration, read docs/schema/schema.sql.
Never guess table names, column names, types or relationships.
- LINQ uses entity property names; raw SQL uses the column names in schema.sql.
- A new column = entity property + IEntityTypeConfiguration change + `dotnet ef migrations add`
+ regenerate the digest (UPDATE_SCHEMA_DIGEST=1 dotnet test --filter SchemaDigest).
- Never edit *ModelSnapshot.cs or an already-applied migration by hand.
- If schema.sql and the code disagree, stop and say so instead of picking one.
Why reference the file instead of pasting the schema into the rule? Cursor's docs are explicit that a file mention inside a rule tells the agent where to look; the agent reads the file with its tools when it needs it, and the contents aren't inlined into the prompt. That's what you want for a large file. Anything that must always be in context belongs in the rule body, which is why the rule itself stays short.
The "project rules" half: what should be always-on
The same mechanism answers the other half of the question, rules that seem to be forgotten. Usually they aren't forgotten; they were never loaded, or they're buried. Cursor's rule types decide when a rule is included:
| Rule type | Frontmatter | Use it for |
|---|---|---|
| Always Apply | alwaysApply: true | A handful of non-negotiables: build/test expectations, layer boundaries, where the decision log lives |
| Apply to Specific Files | globs set, alwaysApply: false | Schema, EF Core, DI and API conventions that only matter in certain folders |
| Apply Intelligently | description only | Situational guidance the agent pulls in when the description matches the task |
| Apply Manually | neither | Playbooks you invoke with @rule-name, such as a migration checklist |
Three checks fix most "Cursor ignores my rules" reports. Rules must be .mdc files in .cursor/rules/; a plain .md file there is ignored. The legacy .cursorrules file is being deprecated, and .mdc rules take precedence where they overlap, so migrate it into an Always Apply rule. And keep always-on rules short: every line is in every request, so a 400-line always-on rule dilutes the instructions that matter. For simple always-on instructions, an AGENTS.md at the repo root is a fine alternative. The full breakdown is in Cursor rules for .NET engineers.
Optional: let the agent query a dev database over MCP
Cursor can use MCP servers, configured per project in .cursor/mcp.json, and there are MCP servers for SQL Server, PostgreSQL and most other databases. Letting the agent inspect a real database is useful for data questions ("how many orders have a null ShippedAt?") and for database-first projects. Treat it as an addition to the digest, not a replacement, and lock it down:
- A read-only database user, created for the agent, with access to a local or dev database only.
- Never production credentials, and never a connection string committed to the repo; use environment variables.
- Keep tool approval on for anything that executes SQL, so you see each query before it runs.
Persist the decisions, not just the schema
A schema digest tells the agent what exists. It doesn't tell it why, and the why is what stops it undoing your decisions. Soft delete through a global query filter, a ban on lazy loading, a reporting context that bypasses tenant filters: those belong in a committed decision log the agent reads at the start of a session:
## ADR-014: Soft delete via global query filter
- Orders, Customers: HasQueryFilter(e => !e.IsDeleted).
- Admin reports call IgnoreQueryFilters() explicitly; nothing else may.
## ADR-015: No lazy loading
- UseLazyLoadingProxies is banned. Load related data with Include or a projection.
Combined with the query guardrails in How to use Cursor AI with EF Core (AsNoTracking on reads, no N+1, bounded Include depth), that's the whole data layer covered: what the schema is, how to query it, and which decisions are settled. The underlying problem, paying to re-explain your system every session, is the one described in The Context Tax.
Checklist
- Generate
docs/schema/schema.sqlwithdotnet ef dbcontext script(or from the database, if database-first) and commit it. - Add the drift test so CI fails when the digest is stale.
- Add a glob-scoped schema rule for
InfrastructureandMigrationsthat points at the digest. - Move any
.cursorrulescontent into a short Always Apply.mdcrule orAGENTS.md. - Record schema-level decisions (filters, loading strategy, naming) as ADRs in a committed log.
- Optionally, add a read-only MCP connection to a dev database.
FAQ
Why does Cursor keep forgetting my database schema?
Because every chat starts without memory, and on an EF Core project the schema is spread across entity classes, fluent configuration, conventions and migrations. The agent usually reads only part of that and guesses the rest. A committed schema digest plus a rule telling the agent to read it fixes most errors.
Should I paste my whole schema into a Cursor rule?
No. Rule bodies are included in the prompt, so a large schema there costs tokens on every request and dilutes other instructions. Keep the schema in a committed file such as docs/schema/schema.sql and reference it from a glob-scoped rule; the agent reads it when it works on data-access code.
How do I generate a SQL schema from an EF Core DbContext?
Run dotnet ef dbcontext script with your project and startup project, which generates CREATE statements from the current model without using migrations. In code, Database.GenerateCreateScript() produces the same script, which makes a simple drift test possible.
Is it safe to connect Cursor to my database?
Only with limits: use a read-only user on a local or development database, keep credentials out of the repository, and leave tool approval on for anything that runs SQL. Never connect an agent to production with write access.
Try one rule free — no email
Copy arch-core-lite.mdc into .cursor/rules/. It stops Cursor (or Copilot in VS) from crossing layer boundaries and shipping EF Core in your Domain layer.
### 1. Respect layer boundaries
- Domain never references Microsoft.EntityFrameworkCore, HttpClient, IConfiguration...
- Application orchestrates via abstractions only. No direct DbContext use.
- Infrastructure implements interfaces declared higher up.
One-time purchase · 30-day refund · or grab the 3-rule email starter if you want more free files.