我使用EF属性值映射到对我强制执行的SQL表和列名。
我还需要在SQL中设置一些默认列值。
在 EF 6 代码优先OnModelCreating不支持在创建数据库时设置 SQL Server 列的默认值。
但是,可以通过代码优先迁移来实现。
以下是我为布尔字段将SQL Server默认值设置为true的示例。
我的实体班级
[Table("Given_TableName_1")]
public class Vehicle
{
[Key,Column("Given_TableColumn_1")]
public int Id { get; set; }
[Column("Given_TableColumn_4")]
public bool IsManual { get; set; }
}
数据库迁移类
public partial class DefaultValueMigrations : DbMigration
{
public override void Up()
{
AlterColumn("Given_TableName_1", "Given_TableColumn_4", c => c.Boolean(nullable: false, defaultValue: true));
}
}
我不想在代码中引用SQL表名。 上面也没有强类型,人们很容易使用字符串字段输入错误。
是否有办法引用实体类名称和属性名称。
类似
AlterColumn(GetClassAttribute(Vehicle,"Table"), GetClassPropertyAttribute(Vehicle.IsManual,"Column"), c => c.Boolean(nullable: false, defaultValue: true));