You can use the NotMapped
attribute data 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; }
[NotMapped]
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);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}