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
Release: 2025-01-13 16:32:43
Original
157 people have browsed it

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; }
Copy after login

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);
}
Copy after login

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; }
Copy after login

Fluent API

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template