Skip to content
← All posts
· Delta1 Labs NebulaObfuscationEF Core

EF Core mapping that survives renaming

EF Core derives table and column names from your CLR type and property names by convention, so an obfuscator that renames Invoice to a quietly points your DbContext at tables and columns that do not exist. Pinning ToTable and HasColumnName is the obvious half; the half that bites is the special cases — the TPH discriminator value that defaults to the CLR type name, owned-type column prefixes, shadow properties, and the migrations snapshot. Here is every place convention couples the schema to a name, and how to freeze the wire names while Nebula.NET renames the members.

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 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:

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.

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.

Default: discriminator value = CLR type nameCreditCardPaymentrenamed → awritesDiscriminator = 'a'row has 'CreditCardPayment'no match ✗ empty resultPinned: HasValue freezes the stored stringCreditCardPaymentrenamed → a (free)HasValue"credit_card"row has 'credit_card'match ✓The discriminator string becomes a literal you own, decoupled from the type identifier the obfuscator renames.

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

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:

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:

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.

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:

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.
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:

{
  "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:

[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, 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:

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.)

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.