code first 創建和初始化數據庫


1.前言 

 Code First是Entity Framework提供的一種新的編程模型。通過Code First我們可以在還沒有建立數據庫的情況下就開始編碼,然后通過代碼對象來生成數據庫。當然我們在實際開發過程當中要做單元測試。進而每次測試的時候 要對庫進行初始化,這樣就不會因上次測試而對本次測試有所影響。下面是具體的實現。

2.建立對象

2.1建立對象

    /// <summary>
    /// model對象
    /// </summary>
    public class model_item : supermodel
    {
        public model_item()
        {
            type = ItemType.Normal;//枚舉類型初始化
        }

        [Required]
        [StringLength(16, MinimumLength = 2)]
        public string name { get; set; }
        [Required]
        [StringLength(16, MinimumLength = 2)]
        public string code { get; set; }
        public ItemType type { get; set; }
        public bool State { get; set; }
        public string Icon { get; set; }
        public long sort { get; set; }
        public long appid { get; set; }
    }

2.2.DBContext

public class GDG_DbContext : DbContext
    {
        public GDG_DbContext() : base("GDG_DbContext") { }
        public DbSet<model_item> model_item { get; set; }
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
         
        }
    }

2.3為對象賦默認值【可選擇】

public class DataInit : IDataInitializer<GDG_DbContext>
    {

    public void Initialize(GDG_DbContext context)    { List<model_item> fim = new List<model_item>() { new model_item(){name="郭德綱",code="gdg",type= ItemType.Normal,State=true,Icon="taoxin.png",sort=0,appid=0,reg_time=DateTime.Now}, new model_item(){name="於謙",code="yq",type= ItemType.Normal,State=true,Icon="juanmao.png",sort=1,appid=1,reg_time=DateTime.Now}, new model_item(){name="德雲社",code="dys",type= ItemType.Normal,State=true,Icon="yun.png",sort=2,appid=2,reg_time=DateTime.Now}, }; fim.ForEach(o => context.model_item.Add(o)); context.SaveChanges(); }
}

 

3.EF Code First

3.1新增

public bool Build()
        {
            try
            {
                var context = new FeeDbContext();
                if (!context.Database.Exists())
                {
                    new List<IDataInitializer<GDG_DbContext>>() { 
                        new DataInit()
                    }.Setup<GDG_DbContext>(context);
                    return true;
                }
                return false;
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder error = new StringBuilder();
                foreach (var item in ex.EntityValidationErrors)
                {
                    foreach (var item2 in item.ValidationErrors)
                    {
                        error.Append(string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage));
                    }
                }
                Console.WriteLine("數據庫初始化報錯:" + error);
                throw ex;
            }
            catch (Exception e)
            {
                Console.WriteLine("數據庫初始化報錯:" + e.Message);
                throw e;
            }
        }

3.2移除

public bool Remove()
        {
            var context = new GDG_DbContext();
            try
            {
                if (context.Database.Exists())
                {
                    return context.Database.Delete();
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("數據庫初始化報錯:" + e.Message);
                return false;
            }
            finally { context.Dispose(); }
        }

3.3初始化

public bool Rebuild()
        {
            return Remove() && Build();
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM