Entity Framework – NotMapped Attribute


If you include a property in the model,EF will attempt to read/write value from/to the database. In case if we want to exclude a property from the model,we just have to set it without a getter or setter.However there is another convenient/right way to do so by using Data Annotations attribute [NotMapped] which is located in System.ComponentModel.DataAnnotations

public class Company
{
   public int CompanyId { get; set; }
   public string CompanyName{ get; set; } 

   [NotMapped]
   public DateTime EstablishedDate { get; set; }
}

Another approach is to use Fluent API as shown below

class ExampleContext : DbContext
    {
        public DbSet<Company> Companies{ get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Company>()
                // here we ignore EstablishedDate from creating
.Ignore(b => b.EstablishedDate);
        }
}

Cavab yaz

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: