最佳答案
我已经在 NET MVC 应用程序中将 [Required]
数据注释添加到我的一个模型中。创建迁移之后,运行 Update-Database
命令会导致以下错误:
无法将值 NULL 插入表“ Director”列中 ‘ MOVIES _ cf7bad808fa94f89afa2e5dae1161e78.dbo.MOVIES’; 列不能 允许空值。 UPDATE 失败。语句已终止。
这是由于一些记录在其 Director
列中具有 NULL。如何自动将这些值更改为某个默认的(比如“ JohnDoe”)控制器?
这是我的模型:
public class Movie
{
public int ID { get; set; }
[Required]
public string Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
[Required]
public string Genre { get; set; }
[Range(1,100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[StringLength(5)]
public string Rating { get; set; }
[Required] /// <--- NEW
public string Director { get; set; }
}
这是我最新的迁移:
public partial class AddDataAnnotationsMig : DbMigration
{
public override void Up()
{
AlterColumn("dbo.Movies", "Title", c => c.String(nullable: false));
AlterColumn("dbo.Movies", "Genre", c => c.String(nullable: false));
AlterColumn("dbo.Movies", "Rating", c => c.String(maxLength: 5));
AlterColumn("dbo.Movies", "Director", c => c.String(nullable: false));
}
public override void Down()
{
AlterColumn("dbo.Movies", "Director", c => c.String());
AlterColumn("dbo.Movies", "Rating", c => c.String());
AlterColumn("dbo.Movies", "Genre", c => c.String());
AlterColumn("dbo.Movies", "Title", c => c.String());
}
}