• MVC中Code First编程一些小技巧


    1. Code First 中实体类

    1. 主建字段
        系统会自动以ID结束的这类创建主键,但有多个这种类型的字段还是指定一个为好
    [Key]
    public int DetailID { get; set; }
    
    2. 非空字段
    [Required,MaxLength(50)] 
    //[StringLength(50)] 同上MaxLength
    public string DetailTitle { get; set; }
    
    3. 设置长度
    [StringLength(500)]
    public string DetailDesc { get; set; }
    
    4. 设置外建字段
         如果StyleID是Style表的主建,可以不用写Foreignkey属性
    [Required, ForeignKey("Style")] 
    public int StyleID { get; set; }
    
    外键关联的Entity
    public virtual Style Style { get; set; }

    5. 指定字段类型:
    [Column(TypeName="Money")]
    public decimal UnitPice { get; set; }

    2. DBContext

        public class StyleContext:DbContext
        {
            public StyleContext() : base("name=WMSAidDB") 
            {
                //自动创建表,如果Entity有改到就更新到表结构
                Database.SetInitializer<StyleContext>(new MigrateDatabaseToLatestVersion<StyleContext, ReportingDbMigrationsConfiguration>());
            }
    
            public DbSet<StyleDetail> StyleDetails { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
           modelBuilder.Entity<UnfulfilledOrderPart>().ToTable("tb_Order");//设置对应的表
           //设置对应的字段格式,长度,非空
                modelBuilder.Entity<UnfulfilledOrderPart>().Property(p => p.OrderNumber).IsRequired().HasColumnType("Varchar").HasMaxLength(500); modelBuilder.Conventions.Remove
    <PluralizingTableNameConvention>(); //表名为类名,不是上面带s的名字 //移除复数表名的契约 modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); //不创建EdmMetadata表 //防止黑幕交易 要不然每次都要访问 EdmMetadata这个表 } } internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<StyleContext> { public ReportingDbMigrationsConfiguration() { AutomaticMigrationsEnabled = true;//任何Model Class的修改將會直接更新DB AutomaticMigrationDataLossAllowed = true; } }

     3.  延迟加载

    EF是默认开启延迟加载,延迟加载的关系表中,必须建立表关系,也就是SQL的FK键

    context.Styles.Include("StyleDetails").Where(p => p.ParentStyleID == ParentID);

     下载Demo

  • 相关阅读:
    ZOJ 2158 Truck History
    Knight Moves (zoj 1091 poj2243)BFS
    poj 1270 Following Orders
    poj 2935 Basic Wall Maze (BFS)
    Holedox Moving (zoj 1361 poj 1324)bfs
    ZOJ 1083 Frame Stacking
    zoj 2193 Window Pains
    hdu1412{A} + {B}
    hdu2031进制转换
    openjudge最长单词
  • 原文地址:https://www.cnblogs.com/chinabc/p/2846062.html
Copyright © 2020-2023  润新知