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

5

I need to insert a property in the template class, but when I enter the code first, it says that 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 ( link ).

How can I mark this property not to generate in the bank?

    
asked by anonymous 04.03.2014 / 15:37

2 answers

4

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

The first is to note the properties of the classes that define your data, the second in the overriding of the OnModelCreating method of your class derived from DbContext.

Picking up your class would look 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);
    }
}

Using Fluent API has the advantage of keeping your classes "clean".
In addition, there are certain types of settings that are not possible through annotations.

See here for everything you can do with the Fluent API.

    
04.03.2014 / 19:34
6

You can do two things:

  • Mark your property with the [NotMapped] attribute (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; }
    }
}
    
04.03.2014 / 16:48