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

How to Ignore Properties in Entity Framework Code First?

Susan Sarandon
Susan SarandonOriginal
2025-01-13 16:18:42790browse

How to Ignore Properties in Entity Framework Code First?

Properties ignored in Entity Framework 4.1 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!

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