Entity Framework 4
Code First
Property Persistence
.NET
Database Management

How not persist property EF4 code first?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In EF4 Code First, public properties are generally treated as mappable unless excluded by convention or configuration. That becomes a problem when an entity contains computed, UI-only, or temporary fields. The correct approach is to explicitly mark those properties as non-persistent so schema and migrations remain clean and your entity model reflects real persisted state.

Why Non-Persistent Properties Exist

Not every property on an entity belongs in the database.

Common examples:

  • Display labels.
  • Calculated totals derived from persisted columns.
  • Transient workflow flags.
  • Values used only for API responses.

If these properties are persisted accidentally, schema grows with noise and future migrations become harder to maintain.

Use NotMapped Attribute

The most direct way is NotMapped.

csharp
1using System.ComponentModel.DataAnnotations.Schema;
2
3public class Invoice
4{
5    public int Id { get; set; }
6    public decimal Subtotal { get; set; }
7    public decimal Tax { get; set; }
8
9    [NotMapped]
10    public decimal Total => Subtotal + Tax;
11
12    [NotMapped]
13    public string DisplayText => $"Invoice #{Id}";
14}

This keeps those properties available in application code while excluding them from table generation.

One practical consequence is that EF cannot translate those members into SQL just because they exist on the class. If a value is derived from mapped columns, it usually has to be computed after materialization or projected explicitly in the query.

Use Fluent API Ignore for Centralized Mapping

If you prefer domain classes without data-annotation attributes, configure exclusion in Fluent API.

csharp
1using System.Data.Entity;
2using System.Data.Entity.ModelConfiguration;
3
4public class InvoiceConfig : EntityTypeConfiguration<Invoice>
5{
6    public InvoiceConfig()
7    {
8        ToTable("Invoices");
9        HasKey(x => x.Id);
10
11        Ignore(x => x.Total);
12        Ignore(x => x.DisplayText);
13    }
14}
15
16public class BillingContext : DbContext
17{
18    public DbSet<Invoice> Invoices { get; set; }
19
20    protected override void OnModelCreating(DbModelBuilder modelBuilder)
21    {
22        modelBuilder.Configurations.Add(new InvoiceConfig());
23        base.OnModelCreating(modelBuilder);
24    }
25}

This pattern is useful when multiple teams share entity classes and mapping policy needs centralized ownership.

Separate Entity and View Models

A common source of persistence bugs is mixing UI concerns into entities. For richer response shape, map entity to a view model instead of adding many non-persistent fields to entity class.

csharp
1public class InvoiceViewModel
2{
3    public int Id { get; set; }
4    public decimal Subtotal { get; set; }
5    public decimal Tax { get; set; }
6    public decimal Total => Subtotal + Tax;
7    public string CurrencyCode { get; set; } = "USD";
8}

This keeps persistence model stable while letting presentation evolve independently.

That separation also makes query intent clearer. Once UI-only fields are out of the entity, it is easier to see which logic belongs in database queries and which logic belongs in application code.

Migration Discipline After Mapping Changes

After adding NotMapped or Ignore:

  1. Generate migration.
  2. Review generated operations manually.
  3. Ensure no unintended column drops appear.
  4. Run integration tests covering queries and projections.

Do not auto-apply migrations blindly. Mapping changes can affect existing deployments if older columns are still used by downstream reporting jobs.

Edge Cases in Legacy EF4 Projects

In older projects, conventions, proxies, and custom base classes can produce surprising mapping behavior. Make exclusion intent explicit and test schema output directly.

Useful checks:

  • Verify table columns in generated database.
  • Verify serialization output for API models.
  • Verify computed properties still work after lazy-loading or proxy configuration.

Explicit tests around mapping are cheaper than production schema rollback.

A practical team standard:

  1. Default entity classes to persisted domain state only.
  2. Mark non-persistent properties explicitly with one method, attribute or Fluent.
  3. Keep mapping review in pull request checklist.
  4. Validate migration diff in CI.

This reduces accidental schema churn over long-lived projects.

Common Pitfalls

  • Assuming getter-only properties are always excluded automatically.
  • Mixing UI-specific fields into persistence entities without explicit exclusion.
  • Forgetting to review migration output after mapping edits.
  • Applying both attribute and Fluent rules inconsistently across modules.
  • Removing persistent columns before verifying all consumers are migrated.

Summary

  • EF4 Code First will attempt to map many public properties unless excluded.
  • Use NotMapped or Fluent Ignore to prevent persistence explicitly.
  • Keep computed and presentation fields out of schema whenever possible.
  • Separate entity and view models for cleaner architecture.
  • Review migration diffs carefully after every mapping change.

Course illustration
Course illustration

All Rights Reserved.