【Code First】 Data Seed

来源:互联网 发布:长板淘宝 编辑:程序博客网 时间:2024/04/28 16:39

File Structure:

File Structure

 

Code Snippet:

    public class TESDbContext : DbContext    {        public TESDbContext()            : base("TESDatabse")        {            // 设置自己的初始化器            Database.SetInitializer<TESDbContext>(new TESDatabaseInitializer());        }        public DbSet<TaskScope> TaskScopes { get; set; }        public DbSet<TaskStatus> TaskStatus { get; set; }        public DbSet<TESUser> TESUsers { get; set; }        public DbSet<Team> Teams { get; set; }    }    public class TESDatabaseInitializer : IDatabaseInitializer<TESDbContext>    {        public void InitializeDatabase(TESDbContext context)        {            if (!context.Database.Exists())            {                context.Database.Create();                this.Seed(context);            }        }        // Initialize stored proc and build-in users.        protected virtual void Seed(TESDbContext context)        {            Team se = new Team();            se.TeamName = "ForAddingBuiltInAdmins";            se = context.Teams.Add(se);            context.SaveChanges();            string builtInUsers = ConfigurationManager.AppSettings["BuiltInAdmins"];            if (string.IsNullOrEmpty(builtInUsers))            {                throw new InvalidDataException("Built-in admin user is not specified.<br/>Please add the following node to the appSetting section of your web.config:<br/>    <add key=\"BuiltInAdmins\" value=\"v-elzhu;v-junweh\"/>");            }            foreach (var user in builtInUsers.Split(';'))            {                TESUser model = new TESUser();                model.Alias = user;                model.DisplayName = user;                model.Roles = 1;                model.RoleNames = "SystemAdmin";                model.TeamId = se.Id;                context.TESUsers.Add(model);            }            context.SaveChanges();            this.AddStortedProcs(context);        }        private string[] Resources = new string[] { "sp_getGroupReport.sql", "sp_getIndividualReport.sql", "sp_getWeeklyTrendReport.sql" };        private void AddStortedProcs(TESDbContext context)        {            string rootFolder = "Wicresoft.MSStore.TES.Data.EntityFramework.SQLScript.";            Assembly asm = Assembly.GetAssembly(typeof(TESDbContext));            try            {                foreach (var item in Resources)                {                    using (StreamReader sr = new StreamReader(asm.GetManifestResourceStream(rootFolder + item)))                    {                        string sp_getGroupReport = sr.ReadToEnd();                        context.Database.ExecuteSqlCommand(sp_getGroupReport);                    }                }            }            catch (Exception ex)            {                if (context.Database.Exists())                {                    context.Database.Delete();                }                throw new Exception("Filed to create necessary stored procedures.ERROR:" + ex.Message);            }        }    }