I have a model in my Blazor app that I want to create a "transitory" attribute for. This attribute is used internally in the app, but I do not want to persist it to the database.
However, when I change my model, it seems that the build process wants to create a database migration and change the database structure, adding the new attribute.
Is there a way to add a non-persistent attribute to the model, that will be ignored for database writes, but can be populated when the model is being handled in the app?
To create attributes on your models without worrying about EF Core automatically mapping the attributes to column in the DB or create migrations, you can annotate these attributes with the [NotMapped]
annotation. This also works at the class level to mark the entire entity as not mapped to a DB table:
public class Foo
{
public int Id { get; set; }
public int SomeValue { get; set; }
// Field will not be mapped to a DB Entity
[NotMapped]
public int Priority {get; set; }
public DateTime CreatedOn { get; set; }
}
// Class will not be mapped to a DB Entity
[NotMapped]
public class Bar
{
public int Id { get; set; }
public int SomeValue { get; set; }
public DateTime CreatedOn { get; set; }
}
See also: exclude-property-if-column-is-not-in-database and learnentityframeworkcore.com/notmapped