Home >Backend Development >C++ >How to Ignore Properties in Entity Framework Code First?
In Entity Framework (EF) 4.1 Code First, it is possible to exclude certain properties from database mapping using the [NotMapped]
property data annotation. This annotation applies to the corresponding property in the entity class.
<code class="language-csharp">public class Customer { public int CustomerID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [NotMapped] public int Age { get; set; } }</code>The
[NotMapped]
attribute is part of the System.ComponentModel.DataAnnotations
namespace.
Also, you can use the Fluent API to override the OnModelCreating
function in the DbContext class.
<code class="language-csharp">protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Customer>().Ignore(t => t.LastName); base.OnModelCreating(modelBuilder); }</code>
Please note that the EF version suggested in the original question is outdated. The latest stable version as of NuGet is EF 4.3.
Update (September 2017): Asp.NET Core (2.0)
For Asp.NET Core 2.0 and above, you can use the previously mentioned [NotMapped]
attribute. In addition, the Fluent API can be used as follows:
<code class="language-csharp">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; } }</code>
The above is the detailed content of How to Ignore Properties in Entity Framework Code First?. For more information, please follow other related articles on the PHP Chinese website!