Ignore table columns in EF Core

c# entity-framework entity-framework-core

Question

I am creating a greenfield application that uses EF Core which must talk to a legacy database. I want EF to ignore some of the columns in the database because they will eventually be deprecated and I don't want them in the new entity model. I can't remove them yet as the legacy system still relies on them.

For an unwanted database column called DeprecatedFeature, I want to do something like:

modelBuilder.Entity<MyEntity>(entity => {
   entity.HasKey(t => t.Id);
   entity.ToTable("MyEntity");
   entity.ColumnIgnore("DeprecatedFeature"); // <-- this is what I want to do
})

Right now, the best I can do is include the property and mark it as obsolete:

public class MyEntity 
{
    public int Id { get; set; }

    [Obsolete("Deprecated in latest version")]
    public string DeprecatedFeature { get; set; }
}

But that means I can't turn on "warnings as errors". I still need to run migrations on my database.

Similar questions: EF 4.x, EF Core skip column on load, Using EF Designer/EDMX and duplicate

Edit

I can see by the answers that there is some confusion about my question:

NotMapped is NOT the answer

NotMapped is used when you have a property in your model that you don't want in the database. My problem is the other way around. I have a column in my database that I don't want in my model.

1
15
4/6/2020 7:51:02 PM

Popular Answer

You have two alternatives:

  1. Using NotMappedAttribute :

    public class MyEntity
    {
         public int Id { get; set; }    
         [NotMapped]
         public string DeprecatedFeature { get; set; }
    }
    
  2. Using FluentAPI:

    modelBuilder.Entity<MyEntity>().Ignore(c => c.DeprecatedFeature );

14
11/1/2017 3:31:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow