# EF Core mapping that survives renaming


Entity Framework Core is a mapping layer, and by default the thing it maps *from* is your names. Declare a class `Invoice` with a property `Status` and, with no configuration, EF concludes there is a table `Invoices` with a column `Status` — convention derives the schema from the CLR identifiers. The moment [Nebula.NET](https://delta1labs.com/products/nebula) renames `Invoice` to `a` and `Status` to `b`, that same convention concludes your database has a table `a` with a column `b`. The queries still compile. The app starts. Then the first read against your real schema fails, or worse, succeeds against the wrong assumption and returns nothing.

The standard advice — pin `ToTable` and `HasColumnName` — is correct and is only half the job. Those two freeze the names you *remember* to freeze. EF derives a handful of other schema values from CLR names by the same convention, and the renamer moves all of them silently. This post is the full inventory, with the emphasis on the cases the obvious advice misses: the inheritance discriminator, owned types, shadow properties, and the migrations snapshot.

## What convention actually couples to a name

Renaming is safe exactly where EF does not reconstruct a name from a CLR identifier at runtime. Convention couples the schema to identifiers in more places than table and column:

1. **Table name** — the `DbSet` property name, or the type name.
2. **Column name** — the property name.
3. **Key, index and foreign-key constraint names** — derived from the member and type names (`PK_Invoices`, `IX_Invoices_Status`, `FK_InvoiceLines_Invoices`).
4. **The TPH discriminator *value*** — for table-per-hierarchy inheritance, the string stored per row to identify the subtype defaults to the subtype's **CLR type name**.
5. **Owned-type column prefixes** — an owned entity's columns are prefixed with the owning navigation's name (`Address_Street`).

LINQ is deliberately *not* on this list. `Where(i => i.Status == open)` compiles to an expression tree holding a `MemberInfo`, not the string `"Status"`; when Nebula renames the property, the `MemberInfo` points at the renamed member and EF translates it through your mapping. Consistent renaming — which Nebula applies across the whole assembly — keeps every compiled query intact. The breakage is always a name that was reconstructed from an identifier, never typed member access.

## Pin the obvious half

The strategy is one idea: make every schema name a string literal in configuration, so the CLR identifiers carry no schema meaning. Fluent configuration in `OnModelCreating` is the clearest place to do it, because it keeps the whole mapping in one reviewable block:

```csharp
protected override void OnModelCreating(ModelBuilder model)
{
    model.Entity<Invoice>(e =>
    {
        e.ToTable("Invoices");
        e.HasKey(x => x.Id).HasName("PK_Invoices");
        e.Property(x => x.Id).HasColumnName("Id");
        e.Property(x => x.Status).HasColumnName("Status");
        e.Property(x => x.Total).HasColumnName("Total").HasPrecision(18, 2);
        e.HasIndex(x => x.Status).HasDatabaseName("IX_Invoices_Status");

        e.HasMany(x => x.Lines)
         .WithOne(l => l.Invoice)
         .HasForeignKey(l => l.InvoiceId)
         .HasConstraintName("FK_InvoiceLines_Invoices");
    });
}
```

Every string there — `"Invoices"`, `"Status"`, `"IX_Invoices_Status"`, `"PK_Invoices"` — is data, not an identifier. Nebula's string encryption protects those literals in the shipped binary, but it never *renames* them, because they are not members. The `x => x.Status` lambdas are typed access that rides the rename automatically. So `Invoice.Status` can become `a.b` in the output while the SQL EF emits still reads and writes the `Status` column.

## The discriminator: the value defaults to the type name

Now the case that the `HasColumnName` advice alone will not save you from. With table-per-hierarchy inheritance, EF stores every subtype in one table and writes a **discriminator** string per row so it knows which type to materialise. You can pin the discriminator *column* name easily enough — but the *value* written into it defaults to each subtype's **CLR type name**, and that is an identifier the obfuscator renames.

```csharp
public abstract class Payment { public int Id { get; set; } }
public class CreditCardPayment : Payment { public string Last4 { get; set; } = ""; }
public class BankTransferPayment : Payment { public string Iban { get; set; } = ""; }
```

With no discriminator configuration, existing rows hold `"CreditCardPayment"` and `"BankTransferPayment"` in the `Discriminator` column. Rename those types to `a` and `b` and EF now writes `"a"` on insert and filters reads with `Discriminator = 'a'` — which matches none of the historical rows. No exception; the subtype query simply returns an empty set.

<figure class="my-8"><svg viewBox="0 0 680 260" role="img" aria-label="Table-per-hierarchy discriminator under obfuscation. By default the discriminator value is the CLR type name, so renaming CreditCardPayment to a makes EF write and filter on the literal a, which does not match existing rows stored as CreditCardPayment. Pinning the value with HasValue freezes the stored string so the CLR type is free to rename." style="width:100%;height:auto"><defs><style>.t{font:600 12px system-ui;fill:#6366f1}.x{font:11px system-ui;fill:#64748b}.m{font:600 11px ui-monospace,monospace;fill:#0f172a}.clr{fill:#eef2ff;stroke:#6366f1}.bad{fill:#fef2f2;stroke:#f87171}.ok{fill:#ecfdf5;stroke:#10b981}.col{fill:#ecfeff;stroke:#0891b2}</style><marker id="rb" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#f87171"/></marker><marker id="rg" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#10b981"/></marker><text class="t" x="16" y="22">Default: discriminator value = CLR type name</text><rect class="clr" x="16" y="34" width="180" height="40" rx="5"/><text class="m" x="28" y="52">CreditCardPayment</text><text class="x" x="28" y="68">renamed → a</text><path d="M196 54 h70" stroke="#f87171" stroke-width="2" fill="none" marker-end="url(#rb)"/><text class="x" x="202" y="46">writes</text><rect class="bad" x="276" y="34" width="150" height="40" rx="5"/><text class="m" x="288" y="59">Discriminator = 'a'</text><path d="M426 54 h40" stroke="#f87171" stroke-width="2" stroke-dasharray="5 4" fill="none" marker-end="url(#rb)"/><rect class="bad" x="476" y="34" width="188" height="40" rx="5"/><text class="m" x="488" y="52">row has 'CreditCardPayment'</text><text class="x" x="488" y="68">no match ✗ empty result</text><text class="t" x="16" y="134">Pinned: HasValue freezes the stored string</text><rect class="clr" x="16" y="146" width="180" height="40" rx="5"/><text class="m" x="28" y="164">CreditCardPayment</text><text class="x" x="28" y="180">renamed → a (free)</text><path d="M196 166 h70" stroke="#10b981" stroke-width="2" fill="none" marker-end="url(#rg)"/><text class="x" x="200" y="158">HasValue</text><rect class="col" x="276" y="146" width="150" height="40" rx="5"/><text class="m" x="288" y="171">"credit_card"</text><path d="M426 166 h40" stroke="#10b981" stroke-width="2" fill="none" marker-end="url(#rg)"/><rect class="ok" x="476" y="146" width="188" height="40" rx="5"/><text class="m" x="488" y="164">row has 'credit_card'</text><text class="x" x="488" y="180">match ✓</text><text class="x" x="16" y="240">The discriminator string becomes a literal you own, decoupled from the type identifier the obfuscator renames.</text></svg></figure>

The fix is to pin both the column *and* a stable value per subtype, so the stored string is a literal you control:

```csharp
model.Entity<Payment>(e =>
{
    e.ToTable("Payments");
    e.HasDiscriminator<string>("PaymentType")
     .HasValue<CreditCardPayment>("credit_card")
     .HasValue<BankTransferPayment>("bank_transfer");
});
```

Now the discriminator column is `PaymentType`, the stored values are `"credit_card"` and `"bank_transfer"`, and both are literals. Nebula can rename `CreditCardPayment` to `a` and EF still writes and matches `"credit_card"`. Pick values that match whatever your existing rows already contain — if the table was created under convention, those are the original type names, so pin `HasValue<CreditCardPayment>("CreditCardPayment")` to keep reading the data you already have.

## Owned types: the prefix comes from the navigation name

An owned entity is stored in its owner's table, and by default each of its columns is prefixed with the owning navigation's name. `Invoice.BillTo` of type `Address` yields columns `BillTo_Street`, `BillTo_City`. Rename the navigation or the owned type's properties and the whole prefix set moves. Pin each column explicitly inside the `OwnsOne` builder:

```csharp
model.Entity<Invoice>().OwnsOne(x => x.BillTo, a =>
{
    a.Property(p => p.Street).HasColumnName("BillTo_Street");
    a.Property(p => p.City).HasColumnName("BillTo_City");
    a.Property(p => p.PostalCode).HasColumnName("BillTo_PostalCode");
});
```

If the owned type is mapped to its own table with `.ToTable(...)`, pin that name too. The rule is the same as everywhere else — once the columns are literals, `Address.Street` is free to become `a.a`.

## Shadow properties are safe — if you access them by schema name

A shadow property has no CLR member at all; it lives only in the EF model, keyed by a string. That means there is nothing for the obfuscator to rename, so shadow properties *survive obfuscation untouched* — provided you both declare and read them by their schema name, never by a CLR identifier that moved:

```csharp
model.Entity<Invoice>().Property<DateTime>("LastModifiedUtc");   // shadow — no CLR member
// ...
var ts = db.Entry(invoice).Property("LastModifiedUtc").CurrentValue;   // string key, safe
```

The danger is the mirror image: using a *string* to reach a **real** CLR member. `EF.Property<InvoiceStatus>(i, "Status")` resolves the member `Status` by name, and a string never follows a rename, so after obfuscation it names a member that no longer exists and throws. Keep string keys for shadow state only; reach real members through typed access.

```csharp
var q1 = db.Invoices.Where(i => EF.Property<InvoiceStatus>(i, "Status") == open); // ✗ throws
var q2 = db.Invoices.Where(i => i.Status == open);                               // ✓ typed
```

## Value conversions keep enums off the member name too

If you store an enum or value object as a string, pin the conversion in configuration rather than relying on `.ToString()` of the CLR member, so the stored text is independent of the renamed type:

```csharp
e.Property(x => x.Status)
 .HasColumnName("Status")
 .HasConversion(
     v => v.ToString(),                                   // or an explicit map
     v => Enum.Parse<InvoiceStatus>(v));
```

For maximum safety when the enum names themselves are sensitive, map through an explicit `HasConversion` dictionary of literals instead of `Enum.Parse`, so neither the column nor the stored values derive from the renamed enum identifiers.

## Migrations: generate from the clean build

Migrations and the model snapshot encode schema names as string literals, so they are safe *when those literals are your pinned names*. Two rules keep them clean:

- **Generate migrations from the non-obfuscated assembly.** The design-time tooling reflects over your model to emit the migration and the `ModelSnapshot`; run `dotnet ef migrations add` against the normal `Debug` build, never the protected artifact. The committed migration then contains your explicit schema literals, and the `__EFMigrationsHistory` table — which stores the `MigrationId` from the `[Migration("...")]` attribute literal — matches regardless of obfuscation.
- **Never write `nameof(SomeProperty)` in a hand-edited migration.** `nameof` captures the CLR name at compile time, so after a rename it emits `"b"` where you meant the column `"Status"`. Write the column name as a literal.

```csharp
migrationBuilder.CreateIndex(
    name: "IX_Invoices_Status",
    table: "Invoices",
    column: "Status");          // literal — never nameof(Invoice.Status)
```

## The config: don't special-case the data layer

Because the schema is pinned in configuration, the entities are ordinary code. The `nebula.config.json` rule is that `MyApp.Data.*` renames with everything else — no blanket exclusion:

```json
{
  "input": "bin/Release/net8.0/MyApp.Data.dll",
  "rename": { "enabled": true },
  "strings": { "encrypt": true },
  "controlFlow": { "enabled": true }
}
```

If one specific feature still reflects over a CLR name at runtime — an auditing shim that records a navigation-property name, say — opt that single member out with an attribute, keeping the exclusion visible where the dependency lives, instead of sparing the whole model:

```csharp
[Obfuscation(Feature = "renaming", Exclude = true)]
public List<InvoiceLine> Lines { get; set; } = new();
```

## Verify the binding before you ship

The failure mode here is silence — an empty subtype query, a null column — so verification is not optional. Do two checks. First, open the protected `MyApp.Data.dll` in [Glass](https://delta1labs.com/products/glass), the free .NET decompiler, and confirm the entity types show as renamed while your `OnModelCreating` still contains the literal strings `"Invoices"`, `"Status"`, `"credit_card"` and the rest — that is what proves the schema vocabulary survived. Second, run an integration test against a database that already holds data, read back one row of each TPH subtype, and assert every mapped column and the discriminator-driven type are correct:

```csharp
var payment = await db.Set<Payment>().SingleAsync(p => p.Id == knownCreditCardId);
Assert.IsType<CreditCardPayment>(payment);                 // discriminator still matches
Assert.Equal("4242", ((CreditCardPayment)payment).Last4);  // column still binds
```

If that test passes against obfuscated binaries and a pre-existing schema, every convention the renamer could have moved has been pinned.

## The shape of the rule

EF Core breaks under obfuscation only where it reconstructs a schema name from a CLR identifier — and convention does that in more places than table and column. Pin all of them: table, column, key, index and constraint names, the discriminator column *and its per-subtype values*, and owned-type column prefixes. Keep string keys for shadow properties only, replace `EF.Property` and `nameof`-in-migrations with typed or literal forms, and generate migrations from the clean build. Then `MyApp.Data.*` obfuscates alongside the rest of the app — renamed, string-encrypted, control-flow-hardened — while the database sees exactly the schema it always has. You protect the domain model that was worth protecting, and the mapping layer costs you nothing. (String encryption and control-flow hardening ship with Nebula Pro; the rename pass this post depends on is in every tier.)

