我已经将[Required]
数据注释添加到ASP.NET MVC应用程序中的其中一个模型中。创建迁移后,运行Update-Database
命令将导致以下错误:
无法将值NULL插入表'MOVIES_cf7bad808fa94f89afa2e5dae1161e78.dbo.Movies'的“ Director”列中;列不允许为空。更新失败。该语句已终止。
这是由于某些记录的Director
列中包含NULL 。如何将这些值自动更改为某些默认值(例如“ John Doe”)导演?
这是我的模型:
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());
}
}