Ignore class attributes in Entity Framework 4.1 Code First
After understanding the limitations of NotAvailableUntil in EF 5, let's explore alternatives to ignoring properties in EF 4.1.
Data annotation
Use the NotMapped property annotation to exclude specific properties from Code-First mapping. For example:
<code>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>
Fluent API
Alternatively, use the Fluent API by overriding the OnModelCreating function:
<code>protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Customer>().Ignore(t => t.LastName); base.OnModelCreating(modelBuilder); }</code>
Correction about [NotMapped] difference
[NotMapped] attribute should prevent columns from being created in the database. If columns are still created despite using annotations, verify that you are using the latest version of EF (4.3).
Asp.NET Core 2.0 and above
In Asp.NET Core 2.0, you can still use the NotMapped attribute annotation:
<code>public class Customer { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [NotMapped] public int FullName { get; set; } }</code>
Or use the Fluent API in your SchoolContext class:
<code>protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Customer>().Ignore(t => t.FullName); base.OnModelCreating(modelBuilder); }</code>
The above is the detailed content of How to Ignore Class Properties in Entity Framework 4.1 and Later?. For more information, please follow other related articles on the PHP Chinese website!