none
EF6.0 code first remap the table when the program is running RRS feed

  • 问题

  • my project has many data to store, so i need to change the mapping table everyday, for example, there is a class A

    public class A
    {
        public int id {get; set;}
        public string data {get;set;}
    }

    today is 11.25 2014, the table name should be "a2014.11.25"

    tomorrow is 11.26 2014 , the table name should be "a2014.11.26"

    the day after tomorrow is 11.27 2014, the table name should be "a2014.11.27"

    so ,what should i do ? even though i call the OnModelCreating() function when the program is running, it does not work, thanks.


    • 已编辑 Anan1688 2014年11月25日 7:01
    2014年11月25日 6:16

答案

  • Hello Anan1688,

    >> today is 11.25 2014, the table name should be "a2014.11.25"tomorrow is 11.26 2014…

    According to your description, it seems that you want to rename your table name according the computer data. If it is, you could use the code first automatic migrations to enable automatic migration for your model and configure the model as below:

    public class CodeFirstContext : DbContext
    
        {
    
            public CodeFirstContext()
    
            {
    
                Database.SetInitializer<CodeFirstContext>(new MigrateDatabaseToLatestVersion<CodeFirstContext, CFs.Migrations.Configuration>());
    
            }
    
            public DbSet<A> As { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
    
            {
    
                modelBuilder.Entity<A>().Map(m => m.ToTable("A" + DateTime.Today.ToShortDateString()));
    
            }
    
        }
    
        public partial class A
    
        {
    
            [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
    
            [Key]
    
            public int AID { get; set; }
    
            public string AName { get; set; }
    
            public string Url { get; set; }
    
        }
    

    Please note, for renaming the table, the application needs to be restarted.

    >>even though i call the OnModelCreating() function when the program is running, it does not work, thanks.

    EF does not provide a remap feature at run time.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年11月26日 6:01
    版主