code firstデータベースの作成と初期化
12271 ワード
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
", 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();
}
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
", 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();
}
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
", 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();
}