DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Why renaming breaks an EF Core compiled model

A team turns on obfuscation for a shipped desktop app, the build is clean, and the app dies on the first database query with InvalidOperationException deep inside EF Core's model builder — a stack trace full of RuntimeModel and AddProperty and not one line of their own code. They had done nothing to EF. What they had done, months earlier, was run dotnet ef dbcontext optimize to shave startup time with a compiled model. Renaming and compiled models do not coexist by default, and the reason is a precise one worth understanding before you reach for the keep-list.

What a compiled model actually is

A normal EF Core DbContext builds its model at runtime by reflecting over your entity classes the first time the context is used. That reflection is not free — for a large model it is tens of milliseconds of pure startup cost. The compiled model removes it. dotnet ef dbcontext optimize walks your model once, at build time, and emits plain C# that reconstructs the same IModel directly, no convention discovery required. You wire it up with one line:

optionsBuilder.UseModel(BlogContextModel.Instance);
Enter fullscreen mode Exit fullscreen mode

The generated code is not magic — it is ordinary source you can open and read. For each entity EF writes a *EntityType.cs with a Create method, and that method is where the trouble lives. Here is the shape of what it emits for a Blog entity with an Id and a Title:

public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
    var runtimeEntityType = model.AddEntityType(
        "MyApp.Data.Blog",
        typeof(Blog),
        baseEntityType,
        propertyCount: 2);

    var id = runtimeEntityType.AddProperty(
        "Id",
        typeof(int),
        propertyInfo: typeof(Blog).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
        field: typeof(Blog).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
        valueGenerated: ValueGenerated.OnAdd);

    // ... Title, keys, indexes ...
    return runtimeEntityType;
}
Enter fullscreen mode Exit fullscreen mode

Read what that AddProperty call depends on. The CLR type comes through typeof(Blog) — a metadata token. But the property is located with the string "Id", and the backing field with the string "<Id>k__BackingField", the compiler-generated name behind an auto-property. The compiled model is, in effect, a second contract laid over your entity types — one expressed almost entirely in reflection strings.

The metadata reason it breaks

Renaming an assembly is not a search-and-replace over text; it edits metadata tables. When Nebula renames the Blog type and its Id property, it rewrites the Name column of the TypeDef row and the Name column of the Property row — Id becomes, say, b. Every token reference to those members is rewritten in lockstep, which is exactly why typeof(Blog) keeps working: it is a TypeRef token, and the obfuscator fixes it up with everything else.

A string literal is not a token. GetProperty("Id") compiles to ldstr "Id", and that "Id" lives in the user-string heap — the #US stream — a blob of UTF-16 text completely separate from the Property table. Renaming never touches #US. So after obfuscation you have a Property row whose name is b and an ldstr that still says Id, and at runtime EF matches the second against the first and finds nothing.

Renaming rewrites the Property table's Name, not the #US string literal the compiled model reflects with — so the lookup misses and model construction throws.

The backing-field lookup fails the same way, and it is the more surprising of the two: <Id>k__BackingField is a private, compiler-synthesised name that most developers never think of as part of a contract. The compiled model made it one.

The failure is a startup crash, not a wrong answer

This is the good news in an otherwise sharp edge. A renamed compiled model does not silently return bad data — it cannot build the IModel at all. AddProperty is handed a null PropertyInfo, and EF raises an InvalidOperationException the first time the context materialises its model. You find out at app launch, in the first integration test that opens a context, not in production three weeks later. Compared with the quiet failures renaming causes elsewhere — a serializer emitting {"b":…}, an options class falling back to defaults — a hard crash on line one is a gift.

The fix: keep the entities, rename everything else

The compiled model reflects over your entity types by string, exactly as a serializer or a reflection-heavy framework does, so it belongs in the same mental box: the names it resolves are a contract, and contracts go on the keep-list. In nebula.config.json:

{
  "schemaVersion": 1,
  "inputs": [ "bin/Release/net8.0/MyApp.dll" ],
  "outputDirectory": "protected",
  "encryptStrings": true,
  "controlFlowObfuscation": true,
  "renaming": {
    "rules": [
      { "pattern": "MyApp.Data.Entities.*", "action": "keep" },
      { "pattern": "MyApp.*",               "action": "rename" }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Two points make this narrower than it looks. First, the keep is on the entity namespace only — your DbContext subclass, your repositories, services, view models and the generated compiled-model classes themselves are all under the broader rename rule and obfuscate normally. The compiled-model classes rename safely because your code references them by type (UseModel(BlogContextModel.Instance)), which the obfuscator rewrites consistently.

Second, note what the keep must cover. A serialized DTO usually needs only its public property names kept, so "members": "public" is enough. A compiled model is greedier: it reflects over the private backing fields too, with their <Name>k__BackingField strings. So an entity keep cannot be narrowed to public members — the backing fields must stay as well, which in practice means keeping the entity type's names wholesale. That is the honest cost, and it is smaller than it sounds: entity classes are typically POCOs whose property names already mirror database columns, so their names were never carrying a secret. You are handing a decompiler the shape of your tables, which it could read from the database anyway, while your actual logic stays renamed.

The alternative: don't ship the compiled model at all

If an app's startup budget is not tight — most desktop and long-running server processes are not — the simplest fix is to stop using a compiled model for the protected build. Drop the UseModel call (or guard it) and EF goes back to building the model by reflecting over the entity types at first use. Runtime reflection over renamed entities works fine as long as EF is discovering members from the types themselves rather than from hardcoded strings, because [Column]/[Table] mappings and convention still operate on the live metadata. You trade a few milliseconds of first-query latency for one fewer thing on the keep-list. Measure first: the compiled model only earns its keep when the model is large and startup latency is a product requirement.

Caveats and when this still bites

The keep-list fixes renaming, but keep two things in mind. If you later add or rename an entity property in source, you must regenerate the compiled model (dotnet ef dbcontext optimize) before you build and obfuscate — a stale compiled model is a bug with or without an obfuscator, but obfuscation makes it look like an obfuscation bug. And if your entity types live in a separate assembly from the one you obfuscate, the keep rule has to target that assembly; a compiled model generated into your main app still reflects across the assembly boundary into the entity project by string.

The one thing you cannot do is let Nebula rename the entities and expect it to "see through" the GetProperty strings. The obfuscator has no way to know that an arbitrary ldstr "Id" is meant to name a member it renamed — it is just text in a heap. That is not a Nebula limitation so much as a property of how string-based reflection works against renamed metadata, and it is the same reason every by-name contract in .NET needs a keep entry.

Takeaway

A compiled model is a performance optimisation that quietly turns your entity property and backing-field names into a reflection contract baked into IL. Renaming rewrites the metadata those strings point at but never the strings, so the compiled model's GetProperty and GetField calls return null and model construction throws at startup. Keep the entity types, let the DbContext and the generated model classes rename, and verify the protected build opens a context before you ship — the mechanism is sharp, but it fails loudly and the fix is two lines of config.

Top comments (0)