C# EF common constraint writing method

Take a note:
The article is transferred from blog Park, original address: EF common constraint writing
Invasion and deletion!

1, Configure constraints through Attribute

1. Primary key constraint

Configure the primary key constraint through KeyAttribute. The code is as follows:

[Key]
public int PrimaryKey{ get; set; }

2. Foreign key constraint

Configure foreign key constraints through ForeignKeyAttribute. The code is as follows:

[Key]
public int PrimaryKey{ get; set; }
[ForeignKey("ForeignKey")]
public int PrimaryKey{ get; set; }

Note that the specified column name exists (foreign key must exist). For example, ForeignKey above, there must be an attribute named ForeignKey in the class.

3. Length constraint

(1) . normal length constraint. Configure the normal length constraint through StringLengthAttribute. The code is as follows:

[StringLength(30)]
public string Name { get; set; }

(2) . maximum length constraint, through MaxLengthAttribute, the code is as follows:

[MaxLength(30)]
public string Name { get; set; }

(3) . minimum length constraint, through MinLengthAttribute, the code is as follows:

[MinLength(30)]
public string Name { get; set; }
 

4. Non NULL constraint

The non NULL constraint is relatively simple. Through the RequiredAttribute, the code is as follows:

[Required]
public string Name{ get; set; }

5. Data type constraints

Configure data type constraints by initializing the TypeName attribute of ColumnAttribute class. The code is as follows:

[Column(TypeName="byte")]
public string Photo{get;set;}
 

6. Field name constraint

By initializing the constructor setting with string parameter of ColumnAttribute class, the code is as follows:

[Column("CTime")]
public DateTime CreateTime { get; set; }
 

7. Table name constraint

Set through the constructor with string parameter of TableAttribute class. The code is as follows:

[Table("Class")]
public class ClassInfo
{}

8. GUID column value

When the primary key value needs to be self GUID, the DatabaseGenerated feature needs to be added on the basis of setting the primary key constraint on the primary key field. The code is as follows:

[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public GUID Id{ get; set; }

If the column value GUID is not set, the database will be filled with 0, and an error will be reported in the second row, because the Id is set as the primary key.

9. Column value + databasegeneratedoption Computed

[Key,DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public GUID Id{ get; set; }

If the attribute is marked as Computed, EF will think that the column is calculated by other columns and will not persist it to the database.

10. Column value + databasegeneratedoption None

[Key,DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id{ get; set; }

This is equivalent to the self increasing effect of Id primary key

11. Ignore mapped columns

When some fields are defined in the entity class, and these fields are obtained through some calculation or combination, we do not need to synchronize them to the database. We can configure to prevent them from being generated into the database. EF is set through the NotMappedAttribute attribute. The code is as follows:

[NotMapped]
public string NotNeeded { get; set; }

12. Ignore table mapping

Ignoring table mapping is the same as ignoring column mapping The code is as follows:

[NotMapped]
public class ClassInfo
{}
 

13. Complex type constraints

Please refer to

The following table is generated according to the specified constraints

[Table("Class")]
public class ClassInfo
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [Required, StringLength(32)]
    public string Name { get; set; }

    [Required, Column("CTime")]
    public DateTime CreateTime { get; set; }

    [Column(TypeName = "ntext"), MaxLength(20), MinLength(10)]
    public string Remark { get; set; }

    [NotMapped]
    public string NotNeed { get; set; }
}

2, Override the OnModelCreating method of DbContext and set the constraints of the corresponding table or field

Copy code

public class ClassInfo
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public DateTime CreateTime { get; set; }

    public string Remark { get; set; }

    public string NotNeed { get; set; }
}
public class EFCodeFirstDbContext : DbContext
{
    public EFCodeFirstDbContext()
        : base("name=connStr")
    {

    }
    /// <summary>
    ///If the entity is mapped to the database, EF will create the table name as the plural form of the entity name. Here is to force the table name to be created as the entity name
    /// </summary>
    /// <param name="modelBuilder"></param>
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<ClassInfo>().ToTable("Class");//Set the table name corresponding to ClassInfo to Class
        modelBuilder.Entity<ClassInfo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);//Set the Id of ClassInfo to self growth
        modelBuilder.Entity<ClassInfo>().HasKey(p => p.Id);//Set the Id property of ClassInfo as the primary key
        modelBuilder.Entity<ClassInfo>().Property(p => p.Name).IsRequired();//Set the Name property of ClassInfo to be non empty
        modelBuilder.Entity<ClassInfo>().Property(p => p.Name).HasMaxLength(32);//Set the maximum length of the Name property value of ClassInfo to 32
        modelBuilder.Entity<ClassInfo>().Property(p => p.CreateTime).IsRequired();//Set the CreateTime property of ClassInfo to be non empty
        modelBuilder.Entity<ClassInfo>().Property(p => p.CreateTime).HasColumnName("CTime");//Set the CreateTime property of ClassInfo to CTime
        modelBuilder.Entity<ClassInfo>().Property(p => p.Remark).HasColumnType("ntext");//Set the Remark property type of ClassInfo to ntext
        modelBuilder.Entity<ClassInfo>().Property(p => p.Remark).HasMaxLength(20);//Set the maximum length of the Remark property value of ClassInfo to 32
        modelBuilder.Entity<ClassInfo>().Ignore(p => p.NotNeed);//Ignore NotNeed field
    }

    public DbSet<ClassInfo> ClassInfo { get; set; }
}

Keywords: C# Database

Added by TimTimTimma on Tue, 22 Feb 2022 03:10:43 +0200