• [转载] EF Code First之FluentAPI 学习


    EF Code First允许我们使用自己的领域类来呈现模型,然后EF会基于这个模型进行查询,跟踪改变,做更新操作等。这个Code-First方式遵循约定大于配置,但是它同样给了我们两种方式,在领域类上添加配置信息。其中一个就是数据注解,另外一个就是使用Code-First's Fluent API。Fluent API 提供了一种以命令的方式,来描述配置。这篇文章中,我将会专注于使用Fluent API的方式。

    现在我们来看看这个FluentAPI怎么用

    第一步:创建一个类库,我把这个类库的名字叫做BF.Entities ,这个类库主要是放了我们的EF的上下文DbContext类等,还有类的模型

    第二步:创建一个模型类 UserInfo类

    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; }   
     }
    

    第三步:在做BF.Entities类库中创建一个单独的存放FluentAPI配置类的文件夹,我取名叫 EntityConfig,然后再里面添加一个名字为 UserInfoConfig的类,用于对UserInfo这个模型类的配置

    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字段
                      }
    		}
    }                        
    

    第四步:既然创建了模型类的 FluentAPI配置类,那总的要使用吧。怎么使用呢?  我们可以去到我们上下文容器类中去配置使用,我们应该在OnModelCreating方法中将所有的配置模型类的 FluentAPI配置类加入到DbModelBuilder容器中

    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; }
        }
    }        
    

    第五步:做好以上配置后,执行下增删改查ToList操作就会根据配置文件中的配置生成数据库表(各个字段名称,字段的类型,是否为空,是否为主键,是否自增 等等)

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

    原文地址:https://blog.csdn.net/Fanbin168/article/details/79603230

  • 相关阅读:
    企业微信自建应用使用审批流程引擎
    unicode和utf8互转【转】
    禅道迅捷版,人人都可用的项目管理工具!
    《2021年IT行业项目管理调查报告》重磅发布!
    wxpython窗体之间传递参数
    go Print 和 反射
    go 接口学习笔记
    设计模式学习笔记
    go 变量逃逸分析
    Go ASM 学习笔记之 ppt 版
  • 原文地址:https://www.cnblogs.com/ghhjanes/p/11220219.html
Copyright © 2020-2023  润新知