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

            */

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