[EntityFramework CodeFirst easy to get started] (3) Example: Create a new CodeFirst entity class[EntityFramework CodeFirst easy to get started] (2) Example: Install CodeFirst development environment

table of Contents

related articles

[EntityFramework CodeFirst easy to get started] (1) Make the data persistence of the class easier

[EntityFramework CodeFirst easy to get started] (2) Example: Install CodeFirst development environment

[EntityFramework CodeFirst easy to get started] (3) Example: Create a new CodeFirst entity class

[Easily get started with EntityFramework CodeFirst] (4) Example: Create a new CodeFirst database session [DbContext, DbSet]

[EntityFramework CodeFirst easy to get started] (5) Example: Use CodeFirst data session and entity class

Contents of this chapter

1. Prepare to build two simple entity classes

2. The default mapping relationship between entity classes and database objects

3. Customize the mapping relationship between entity classes and database objects

4. Use the Data Annotation feature to mark the mapping relationship between custom entity classes and database objects

5. Use Fluent API code to customize the mapping relationship between entity classes and database objects


1. Prepare to build two simple entity classes

We continue to use the EntityFrameworkCodeFirst sample project, ready to add some simple entities under the project. We assume that two entity classes are created for a company, one is a department (named Department) and the other is an employee (named Staff), as shown in the figure.

Department attributes: department serial number Id, department number Code, department name Name, department staff list Staffs.

Attributes of employee staff: employee serial number Id, employee number Code, employee name Name, department to which they belong, department ID to which they belong.

The relationship between Department and Staff: Each staff is affiliated to a certain department, and a department may contain multiple staff.

The code of the entity class is as follows:

/// <summary>/// 部门/// </summary>public class Department{        /// <summary>    /// Id    /// </summary>    public long Id { get; set; }     /// <summary>    /// 编码    /// </summary>    public string Code { get; set; }     /// <summary>    /// 名称    /// </summary>    public string Name { get; set; }     /// <summary>    /// 员工集合    /// </summary>    public virtual ICollection<Staff> Staffs { get; set; } }
/// <summary>/// 员工/// </summary>public class Staff{    /// <summary>    /// Id    /// </summary>    public long Id { get; set; }     /// <summary>    /// 编码    /// </summary>    public string Code { get; set; }     /// <summary>    /// 名称    /// </summary>    public string Name { get; set; }     /// <summary>    /// 所属部门Id    /// </summary>    public long DepartmentId { get; set; }      /// <summary>    /// 所属部门    /// </summary>    public virtual Department Department { get; set; } }

2. The default mapping relationship between entity classes and database objects

By default, no special syntax or additional statements are required, and entity classes can automatically correspond to database objects. As the main object of the database, the data table corresponds to the entity class one-to-one, and the fields of the data table correspond to the attributes of the entity class one-to-one. In general, as shown in the table:

databaseEntity classExample
Entity elementDatabase element
Table NamePlural form of class nameDepartment, StaffDepartments, Staffs
Table ownerdbo dbo.Departments, dbo.Staffs
Field nameClass attribute nameDepartment.Code, Staff.NameDepartments.Code, Staffs.Name
Primary keyAn attribute named "Id" or "class name Id"Department.Id, Staff.IdDepartments.Id(PK_dbo.Departments), Staffs.Id(PK_dbo.Staffs)
Foreign keyThe type is an attribute of another entity, or the collection attribute that implements Icollection and the member type of the collection is another entityDepartment.Staffs, Staff.DepartmentStaffs.DepartmentId(FK_dbo.Staffs_dbo.Departments_DepartmentId)

3. Customize the mapping relationship between entity classes and database objects

If you want to define the correspondence between entity types and database objects in more detail, you only need to add a small amount of special code. There are two specific ways: using Data Annotation feature mark, using Fluent API code.

4. Use the Data Annotation feature to mark the mapping relationship between custom entity classes and database objects

Add references to entity classes

using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;

Add tags to entity classes and their attributes

/// <summary>/// 部门/// </summary>public class Department{    /// <summary>    /// Id    /// </summary>    [Key] //主键    public long Id { get; set; }      /// <summary>    /// 编码    /// </summary>    [Required] //必需的    [StringLength(100)] //字符串的最大长度    public string Code { get; set; }     /// <summary>    /// 名称    /// </summary>    [Required] //必需的    [StringLength(200)] //字符串的最大长度    public string Name { get; set; }      /// <summary>    /// 员工集合    /// </summary>    [InverseProperty("Department")] //导航属性的对应关系    public virtual ICollection<Staff> Staffs { get; set; }  }
/// <summary>/// 员工/// </summary>public class Staff{    /// <summary>    /// Id    /// </summary>    [Key] //主键    public long Id { get; set; }      /// <summary>    /// 编码    /// </summary>    [Required] //必需的    [StringLength(100)] //字符串最大长度    public string Code { get; set; }     /// <summary>    /// 名称    /// </summary>    [Required] //必需的    [StringLength(200)] //字符串最大长度    public string Name { get; set; }     /// <summary>    /// 所属部门Id    /// </summary>    public long DepartmentId { get; set; }     /// <summary>    /// 所属部门    /// </summary>    [ForeignKey("DepartmentId")] //导航属性对应的外键属性    public virtual Department Department { get; set; }   }

There are many similar features, you can view the following assembly through the Object Browser: System.ComponentModel.DataAnnotations. Each feature contains a summary description. As shown in the figure.

5. Use Fluent API code to customize the mapping relationship between entity classes and database objects

The two methods are the same in the same way. I prefer to use the Data Annotation mark, which is integrated with the code of the class and is more intuitive. From my practice, Data Annotation can handle most situations, but sometimes the additional Fluent API code can solve some special needs.

Let me take a look at the Fluent API. Simply put, it is to rewrite an event in the context DbContext: OnModelCreating(DbModelBuilder modelBuilder). The sample code is as follows:

protected override void OnModelCreating(DbModelBuilder modelBuilder){    //Department    modelBuilder.Entity<Department>().HasKey(m=>m.Id); //主键    modelBuilder.Entity<Department>().Property(m => m.Code).IsRequired(); //必需的    modelBuilder.Entity<Department>().Property(m => m.Code).HasMaxLength(100); //字符串最大长度    modelBuilder.Entity<Department>().Property(m => m.Name).IsRequired().HasMaxLength(200); //必需的 //字符串最大长度    modelBuilder.Entity<Department>().HasMany(m => m.Staffs).WithRequired(m => m.Department).HasForeignKey(m => m.DepartmentId); //导航属性的对应关系及外键定义                //Staff    modelBuilder.Entity<Staff>().HasKey(m => m.Id); //主键    modelBuilder.Entity<Staff>().Property(m => m.Code).IsRequired(); //必需的    modelBuilder.Entity<Staff>().Property(m => m.Code).HasMaxLength(100); //字符串最大长度    modelBuilder.Entity<Staff>().Property(m => m.Name).IsRequired().HasMaxLength(200); //必需的 //字符串最大长度}

The two methods can complement or duplicate each other, but there should be no ambiguity.

To know how DbContext and more content, and listen to the next time decomposition.

Take a break, take a break.