EF FluentApi 配置模型属性映射的几种方式

           //设置映射的表名为T_Class
            this.ToTable(nameof(T_Class));

            //设置字符串属性最大字符串长度为50
            //生成字段类型为nvarchar(11)
            this.Property(i => i.ClassName).HasMaxLength(50);

            //设置字符串属性最大字符串长度为11
            this.Property(i => i.ClassPhoneNum).HasMaxLength(11);

            //设置字符串属性ClassPhoneNum为固定长度,长度为上面字符串属性设置的最大长度,
            //生成字段类型为nchar(11)
            this.Property(i => i.ClassPhoneNum).IsFixedLength();
           // this.Property(i => i.ClassPhoneNum).HasMaxLength(11).IsFixedLength();链式简写方式

            //设置属性可以为空(null),若不可为空是IsRequired()
            this.Property(i => i.ClassNum).IsOptional();

            //设置主键,默认为Id
            this.HasKey(i => i.Id);

            //设置IsGoodClass字段不映射到数据库
            this.Ignore(i => i.IsGoodClass);

            //设置属性Desc对应数据库中的字段名为ClassDesc
            this.Property(i => i.Desc).HasColumnName("ClassDesc");

            //指定字段是自动增长类型
            this.Property(i => i.MarkId).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);


            //在主表中配置主从表关系
            this.HasMany(i=>i.T_Students).WithRequired(t => t.Class)
             .HasForeignKey(t => t.ClassId).WillCascadeOnDelete();

            /*
           //也可以在从表中配置主从表关系,若在从表中配置,需把下面的配置写到从表的配置文件中
           this.HasRequired(t => t.Class).WithMany(t=>t.T_Students)
           .HasForeignKey(t => t.ClassId);
            */

            /*
            
            //设置对应的数据类型是varchar,而不是nvarchar
            this.Property(i => i.ClassName).IsUnicode(false);

            */

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章