Home > Backend Development > C++ > How to Ignore Class Properties in Entity Framework 4.1 and Later?

How to Ignore Class Properties in Entity Framework 4.1 and Later?

Patricia Arquette
Release: 2025-01-13 16:22:17
Original
411 people have browsed it

How to Ignore Class Properties in Entity Framework 4.1 and Later?

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

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

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

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

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!

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