Raheel Khan Raheel Khan - 5 months ago 38
C# Question

Ignoring a class property in Entity Framework 4.1 Code First

My understanding is that the

attribute is not available until EF 5 which is currently in CTP so we cannot use it in production.

How can I mark properties in EF 4.1 to be ignored?

UPDATE: I noticed something else strange. I got the
attribute to work but for some reason, EF 4.1 still creates a column named Disposed in the database even though the
public bool Disposed { get; private set; }
is marked with
. The class implements
of course but I don't see how that should matter. Any thoughts?


You can use the NotMapped Annotation to instruct Code-First to exclude a particular property

public class Customer
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    public int Age { set; get; }

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);


The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.