How to prevent a property from being mapped to an entity in the Entity Framework?

Asked

Viewed 4,310 times

7

I need to enter a property in the model class, but when I enter the code first, it says the table already exists and changes have been made.

My code:

public class Data
{        
    [Key]
    public int Id { get; set; }        
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public Nullable<System.DateTime> Date { get; set; }

    //public bool Selected { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

If I uncheck the Selected property it gives this error:

The model backing the 'Context' context has changed Since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/? Linkid=238269).

Can I mark this property not to generate in the bank?

  • You have to migrate in order to change a model. New to Asp mvc?

  • Try to use the annotation [NotMapped] on the property.

  • [NotMapped] works for calculated field, that’s what he wants?

2 answers

7

You can do two things:

  • Mark your property with the attribute [NotMapped] (recommended):
public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}
  • Create a partial class of the template class that must be in the same namespace:
namespace NamespaceDaClasseModelo
{
    public class partial NomeDaClasseModelo
    {
        public string NomeDaNovaPropriedade { get; set; }
    }
}

5


The Entity Framework has two ways to change the way the database is configured, Annotations or EF Fluent API.

The first consists of annotating the properties of the classes that define your data, the second, in the "Overriding" of the method OnModelCreating of its class derived from DbContext.

Taking in your class would be like this:

Annotations

public class Data
{        
    [Key]
    public int Id { get; set; }        
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime? Date { get; set; }

    [NotMapped]        
    public bool Selected { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

Fluent API

public class SeuContext : DbContext
{
    public DbSet<Data> {get; set;}
    .....
    .....
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Data>().Ignore(d => d.Selected);
    }
}

The use of Fluent API has the advantage of keeping their classes "clean".
In addition, there are certain types of settings that are not possible to make through annotations.

Behold here everything you can do with the Fluent API.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.