Home >Backend Development >C++ >How to Ignore Class Properties in Entity Framework Code First?

How to Ignore Class Properties in Entity Framework Code First?

Linda Hamilton
Linda HamiltonOriginal
2025-01-13 16:32:43158browse

How to Ignore Class Properties in Entity Framework Code First?

Ignoring a Class Property in Entity Framework 4.1 Code First

In Entity Framework (EF) 4.1, you may encounter the need to exclude certain properties from being included in the database schema. Fortunately, there are two approaches to achieve this.

[NotMapped] Attribute

This attribute is part of the System.ComponentModel.DataAnnotations namespace and can be applied to properties to indicate they should be ignored by EF.

[NotMapped]
public int Age { get; set; }

Fluent API

Alternatively, you can employ the Fluent API to override the OnModelCreating function within your DBContext class:

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

Additional Notes

  • [NotMapped] works in EF versions 4.1 and later.
  • The Fluent API approach is available in all versions of EF.
  • Properties marked as [NotMapped] will not be mapped to columns in the database, even if they are part of an IDisposeable implementation.

Asp.NET Core (2.0)

For newer versions of EF, the approach is similar:

[NotMapped] Attribute

[NotMapped]
public int FullName { get; set; }

Fluent API

modelBuilder.Entity<Customer>().Ignore(t => t.FullName);

By using these techniques, you can effectively exclude properties from being mapped to the database, allowing for flexibility in your data modeling.

The above is the detailed content of How to Ignore Class Properties in Entity Framework Code First?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn