数据列类型描述
DataType特性
DataType 属性用于指定比数据库内部类型更具体的数据类型。
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
StringLength
StringLength
特性设置数据库中的最大长度,并为 ASP.NET Core MVC
提供客户端和服务器端验证。 还可在此属性中指定最小字符串长度,但最小值对数据库架构没有影响。
还支持RegularExpression表达式
[RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
Column 特性
假设在名字字段使用了 FirstMidName
,这是因为该字段也可能包含中间名。 但却希望将数据库列命名为 FirstName
,因为要针对数据库编写即席查询的用户习惯使用该姓名。 若要进行此映射,可使用 Column
特性。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ContosoUniversity.Models
{
public class Student
{
public int ID { get; set; }
[StringLength(50)]
public string LastName { get; set; }
[StringLength(50)]
[Column("FirstName")]
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
}
更新这些属性后,都需要进行数据库迁移
执行
add-migration
update-database