我的 Blazor 应用程序中有一个模型,我想为其创建“临时”属性。该属性在应用程序内部使用,但我不想将其保存到数据库中。
但是,当我更改模型时,构建过程似乎想要创建数据库迁移并更改数据库结构,添加新属性。
有没有办法向模型添加非持久属性,该属性在数据库写入时将被忽略,但可以在应用程序中处理模型时填充?
要在模型上创建属性,而不用担心 EF Core 自动将属性映射到数据库中的列,您可以使用
[NotMapped]
注释来注释这些属性。
这适用于班级级别和个人属性:
// Class will not be mapped to a DB Entity
[NotMapped]
public class Foo
{
public int Id { get; set; }
public int SomeValue { get; set; }
public DateTime CreatedOn { get; set; }
}
public class Bar
{
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; }
}
另请参阅:exclude-property-if-column-is-not-in-database 和 learnentityframeworkcore.com/notmapped