Exclude properties for migrations

.net ef-migrations entity-framework-core

Question

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?

1
1
8/23/2018 3:01:42 PM

Accepted Answer

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 };
3
8/23/2018 3:02:03 PM

Popular Answer

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.



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