EFCore CodeFirst 注解特性

1. [Table]

Table特性可以应用于一个领域类上面,用来在数据库中生成相应名称的数据表。它重写了EF 6和 EF Code 中默认的约定,根据默认约定,EF 6和EF Core创建的表的名称是实体名称+s(或者es),并且创建的数据表的列名称和实体属性名称一样。

* Table Attribute: [Table(string name, Properties:[Schema = string])

name:数据表的名称

Schema:数据库的模式名称【可选的】

如下Student类:数据库生成的表名为Sc.StudentInfo

[Table("StudentInfo",Schema="Sc")]
public class Student
{
    public int StudentID { get; set; }

    public string Name { get; set; }
}

2. [Key]

标识字段为主键。如果是多个字段都标识了[key],则默认生成联合主键。

3. [Column]

Column特性,可以应用于实体的一个或者多个属性上面,用来配置数据库中数据表中列的列名、列的数据类型以及列的先后顺序。Column特性重写了默认的约定。按照EF 6和EF Core中的默认约定,将会创建和属性相同的列名称,并且数据表,列的顺序和实体中属性的顺序一致。

* Column Attribute: [Column (string name, Properties:[Order = int],[TypeName = string])

name:表的数据列的名称

Order:列的顺序,从索引0开始【可选的】

TypeName:列的类型名称【可选的】

如下AddTime列:数据库生成的字段将是“CreateTime”而不是实体类中的AddTime,类型是“Date”而不是默认的DateTime。

[Table("StudentInfo",Schema="Sc")]
public class Student
{
    public int StudentID { get; set; }

    public string Name { get; set; }
    
    [Column("CreateTime",TypeName="Date")]
    public DateTime AddTime { get; set; }
}

4. [Required]

Required特性可以应用于一个实体的一个或多个属性上面。EF将会为标识Required特性的属性,在数据库表的列中生成不为空(not null)的列。

5. [StringLength] 与 [MaxLength]

StringLength特性可以应用于实体的string类型的属性上,它指定了属性的所允许的最大字符长度,然后对应在数据库中就生成相应长度的数据列(在SQL Server数据库中是,nvarchar类型)。

MaxLength特性指定了属性的值所允许的最大值,然后在数据库中就生成相应列的最大值。MaxLength特性可以应用于实体的String类型的属性和byte[]数组类型的属性上。

区别:[MaxLength] 适用的类型比[StringLength]多。

6. [NotMapped]

当我们不想实体类中的某个或者某些属性,不要映射成数据库中的列的时候。可以使用NotMapped特性,标识NotMapped特性在属性上面就行了。默认情况下,EF为实体的每个属性映射数据列。【必须包含get;和set;】。NotMapped特性重写了这个约定。

需要注意的是:EF不会为没有get;和set;的属性,创建列。

7. [Index]

用来在特定的列上面创建索引,默认情况下,索引的名称是IX_{属性的名称}。

* Column Attribute: [Index(string name, Properties:[IsClustered = bool],[IsUnique= bool])

name:索引名称

IsClustered : 是否是建聚合索引

IsUnique:是否是唯一索引

如下Name字段,数据库创建的索引名称“Idx_Student_Name”,为聚合索引,唯一索引。

[Table("StudentInfo",Schema="Sc")]
public class Student
{
    public int StudentID { get; set; }
    
    [Index("Idx_Student_Name",IsClustered=true,IsUnique=true)]
    public string Name { get; set; }
    
    [Column("CreateTime",TypeName="Date")]
    public DateTime AddTime { get; set; }
}

8. [ForeignKey]

在EF 6和EF Core中,数据注解中的ForeignKey特性,是用来在两个实体间配置外键关系。

根据默认的约定,当属性的名称与相关实体的主键属性匹配时,EF将该属性作为外键属性。

ForeignKey Signature: [ForeignKey(name string)]
name:相关联的导航属性的名称或者相关联的外键属性名称

一般用法:

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    [ForeignKey("TeacherId")]
    public Teacher teacher{ get; set; }
}

public class Teacher
{
    public int TeacherId { get; set; }
    public string TeacherName { get; set; }
}

 

 

 

 

 

你可能感兴趣的:(C#,数据库,数据库,ef,codefirst,注解,[table])