我首先使用带有 EF 代码的 ASP.NET MVC。
在我的模型中,我有一个可以为空的属性:
public byte[] Avatar { get; set; }
但是,当我运行 update-database 时,我得到:
无法将值 NULL 插入到列“Avatar”、表“temp”中;列不允许空值。更新失败。
我没有指定所需属性的数据注释,该属性也不是外键。
有任何想法吗?
进一步更新:
如果我删除我的数据库并使用“update-database -verbose”强制创建一个新数据库,那么我可以看到正在创建的表专门在我的字段上强制使用 NOT NULL 标志:
CREATE TABLE [dbo].[UserProfile] (
[UserId] [int] NOT NULL IDENTITY,
[UserName] [nvarchar](max),
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[EmailAddress] [nvarchar](50) NOT NULL,
[WorkPhone] [nvarchar](20),
[MobilePhone] [nvarchar](20),
[HireDate] [datetime],
[Avatar] [image] NOT NULL,
[AvatarMimeType] [nvarchar](max),
CONSTRAINT [PK_dbo.UserProfile] PRIMARY KEY ([UserId])
)
我的完整模型:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
[Required]
[Display(Name = "First name")]
[MaxLength(50, ErrorMessage = "First Name cannot be longer than 50 characters.")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[MaxLength(50, ErrorMessage = "Last Name cannot be longer than 50 characters.")]
public string LastName { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
[Required]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$", ErrorMessage = "Not a valid email address")]
[Display(Name = "Email Address")]
[MaxLength(50, ErrorMessage = "Email Address cannot be longer than 50 characters.")]
public string EmailAddress { get; set; }
[Display(Name = "Work Phone")]
[MaxLength(20, ErrorMessage = "Work Phone cannot be longer than 20 characters.")]
public string WorkPhone { get; set; }
[Display(Name = "Mobile Phone")]
[MaxLength(20, ErrorMessage = "Mobile Phone cannot be longer than 20 characters.")]
public string MobilePhone { get; set; }
[Display(Name = "Hire Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? HireDate { get; set; }
[ValidateFile(ErrorMessage = "Please select a PNG, JPG or GIF image smaller than 2MB")]
[Column(TypeName = "image")]
public byte[] Avatar { get; set; }
public string AvatarMimeType { get; set; }