4

I have properties on my model that I don't want to generate fields in the tables after a migration.

Is it possible to exclude properties for Entity Framework Core migrations?

Is there an attribute for the model or some Fluent API method on my DbContext for this?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Alpha75
  • 2,140
  • 1
  • 26
  • 49

2 Answers2

10

You should be able to specify [NotMapped] as a data annotation above the property.

E.g. if you wanted to have FullName in your model which consisted of FirstName and LastName you would do:

public string FirstName { get; set; }
public string LastName { get; set; }

[NotMapped]
public string FullName { get;set };
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
SashaStojanovic
  • 331
  • 3
  • 15
3

The Ignore method is usd to specify that the auto-implemented FullName property in the Contact class below is excluded from mapping:

public class SampleContext : DbContext
{
    public DbSet<Contact> Contacts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Contact>().Ignore(c => c.FullName);
    }
}

public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName => $"{FirstName} {LastName}";
    public string Email { get; set; } 
}

Note: Data Annotations equivalent to the Ignore method is the NotMapped attribute.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197