Câu trả lời được chấp nhận là chính xác, chỉ cần cập nhật với giải pháp EF Core; (còn giải pháp của tôi tập trung vào việc thay đổi giá trị mặc định, thay vì tạo đúng giá trị lần đầu tiên)
Vẫn không có thuộc tính Dữ liệu.
Và bạn vẫn phải sử dụng API thông thạo; nó có một HasDefaultValue
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Rating)
.HasDefaultValue(3);
}
Lưu ý, cũng có HasDefaultValueSql
là đối với trường hợp NULL:
.HasDefaultValueSql("NULL");
Và bạn cũng có thể sử dụng Migrations Up
và Down
phương pháp, bạn có thể thay đổi defaultValue
hoặc defaultValueSql
nhưng bạn có thể cần phải giảm chỉ mục trước. Dưới đây là ví dụ:
public partial class RemovingDefaultToZeroPlantIdManualChange : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_TABLE_NAME_COLUMN_NAME",
table: "TABLE_NAME"
);
migrationBuilder.AlterColumn<int>(
name: "COLUMN_NAME",
table: "TABLE_NAME",
nullable: true,
//note here, in the Up method, I'm specifying a new defaultValue:
defaultValueSql: "NULL",
oldClrType: typeof(int));
migrationBuilder.CreateIndex(
name: "IX_TABLE_NAME_COLUMN_NAME",
table: "TABLE_NAME",
column: "COLUMN_NAME"
);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_TABLE_NAME_COLUMN_NAME",
table: "TABLE_NAME"
);
migrationBuilder.AlterColumn<int>(
name: "COLUMN_NAME",
table: "TABLE_NAME",
nullable: true,
//note here, in the Down method, I'll restore to the old defaultValue:
defaultValueSql: "0",
oldClrType: typeof(int));
migrationBuilder.CreateIndex(
name: "IX_TABLE_NAME_COLUMN_NAME",
table: "TABLE_NAME",
column: "COLUMN_NAME"
);
}
}
Nguồn
2017-06-01 01:40:36
Tuyệt vời, cảm ơn, tôi sẽ thực hiện việc này ngay bây giờ. – Carl
Bạn được chào đón;) –