[Reserved] EF Code First of FluentAPI learning

EF Code First allows us to use their own domain class to render the model, then EF will be based on this model queries, track changes, and so do the update. The Code-First way is greater than follow the convention configuration, but it also gives us two ways to add configuration information in the field of class. Wherein the annotation data is a, the other one is to use Code-First's Fluent API. Fluent API provides a way in order to describe the configuration. In this article, I will focus on ways of using the Fluent API.

 

Now let's see how to use this FluentAPI

Step 1: Create a class library, I put this library name is BF.Entities, this library is mainly put context DbContext class of our EF, etc., as well as class model

 

Step 2: Create a model class UserInfo class

public class UserInfo

{
      public int Id { get; set; }
      public string Name { get; set; }
      public int? Age { get; set; }
      public int? Gender { get; set; }
      public string Mobile { get; set; }
      public string Email { get; set; }
      public string Addres { get; set; }
      public string Reamarks { get; set; }
      public int? LoginId { get; set; }   
 }

Step 3: Create a separate storage FluentAPI class configuration folder do BF.Entities library, I named the EntityConfig, and then add a name for UserInfoConfig inside the class, this model is used to configure the UserInfo class

namespace BF.Entities.EntityConfig

{
      //EntityTypeConfiguration<UserInfo>表示对UserInfo模型类做配置
      public class UserInfoConfig : EntityTypeConfiguration<UserInfo>
      {
          public UserInfoConfig()
          {
              this.ToTable("T_UserInfo"); //设置UserInfo这个模型类对应数据库中的T_UserInfo表
              this.HasKey(r => r.Id); //设置Id属性为主键
              this.Property(r => r.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);//设置Id是自动增长类型的

              this.Property(r => r.Name).IsRequired();//设置Name属性不能为空

              this.Property(r => r.Name).HasMaxLength(20);//设置Name属性的最大长度为30 (如果不设置表示最大长度,数据库中对应是的nvarchar(MAX)类型)

              this.Property(r => r.Email).IsOptional();//设置Email属性可以为空(因为Email一般是string类型的,string类型一般是可以为空的,所以这样设置一般没有必要)
              this.Property(r => r.Age).IsOptional();//设置Age属性可以为空(如果一个数值类型可以为空,我们一般在模型类后的类型后就加一个?就可以了,例如 public int? Age{get;set;} 所以也这样设置一般也没有必要)

              this.Property(r => r.Email).IsUnicode(false);//设置Email属性映射到数据库中的类型是varchar类型,而不是nvarchar类型
              this.Property(r => r.Mobile).HasMaxLength(11).IsFixedLength();//设置Mobile属性的最大长度是为11,并且固定长度(例如数据库字段类型是nchar(11),那么如果你 插入的数据是10个,那么在数据后面自动补上一个空格,组成11的长度)
              this.Ignore(r => r.Reamarks);//设置模型类的Reamarks属性不参与映射到数据库表
              this.Property(r => r.Gender).HasColumnName("Sex");//设置模型中的Gender属性对应与数据表中的Sex字段
                  }
        }
}                        

Step Four: Now create a FluentAPI configuration class model class, that always want to use it. How to use it? We can go to our context used to configure the container class, we should all FluentAPI configuration class configuration model class DbModelBuilder added to the vessel in the method OnModelCreating

namespace BF.Entities

{
      public class BFDbContext : DbContext
      {
          public BFDbContext()
              : base("name=ConnStr")
          {
              base.Database.CreateIfNotExists();         

          }
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
              base.OnModelCreating(modelBuilder);

              var s = Assembly.GetExecutingAssembly().FullName;
              //modelBuilder.Configurations.AddFromAssembly()表示从指定程序集中加载所有继承自EntityTypeConfiguration<>的类到配置中
              modelBuilder.Configurations.AddFromAssembly(
                  Assembly.GetExecutingAssembly());
              //Assembly.GetExecutingAssembly()表示拿到当天运行的这段代码所在的程序集
              //而这段代码所在的程序集就是EntityConfig文件夹下面的所有Config配置文件所在的程序集,例如UserInfoConfig
              //当然,如果你的配置文件全写在一个例如“ModelConfig.dll”的程序集中,那么这段Assembly.GetExecutingAssembly()代码就应该改成Assembly.Load("ModelConfig");
              //以上这段代码也可以这样写,但是不推荐这样的写法,因为写在这里,项目大了的话,大家都改这个文件会比较乱套
        //例如针对UserInfo这个模型类我们可以直接在这里将加入到DbModelBuilder配置中
        //如:modelBuilder.Entity<UserInfo>().ToTable("T_UserInfo");等等
        //或者在UserInfoConfig中配置好,然后单独将它加入到DbModelBuilder配置中
        //如:modelBuilder.Configurations.Add(new UserInfoConfig());
       
    }

    public DbSet<UserInfo> UserInfo { get; set; }
    public DbSet<UserLogin> UserLogin { get; set; }
    }
}        

Step Five: do the above configuration, the next execution ToList CRUD operations according to the configuration file will generate a database configuration table (each field name, type field is empty, if the primary key, and so whether the self-energizing )

 public class HomeController : Controller

{
      public ActionResult Index()
      {
          BFDbContext db = new BFDbContext();
          var a = db.UserInfo.ToList();
          return View();
      }
 }

Original Address: https://blog.csdn.net/Fanbin168/article/details/79603230

Guess you like

Origin www.cnblogs.com/ghhjanes/p/11220219.html