数据迁移一篇比较好的文章:https://www.cnblogs.com/dotnet261010/p/7912818.html
entity framework开发中,难免会有一些创建数据库和数据 表的时候,那么初始化的时候,我们希望 能够一并向数据库中填入一些初始数据。如下几种方法,供参考。
code first有两种配置数据库映射的方式,DataAnnotation 和 Fluent API。然后如下我使用的是DataAnnotation。DataAnnotation的配置方式就是需要给定义实体和值对象的类和类中的属性加上与数据库映射相关的配置标签。但是 Fluent API的功能比DataAnnotation强大,因为FluentAPI支持索引,而DataAnnotation貌似没找到相应功能。
先看model
Department
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace EntityFrameWorkDemo
{
public class Department
{
[Key]
[Column(TypeName = "nvarchar")]
[StringLength(30)]
public string Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public List<Employee> Employees { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace EntityFrameWorkDemo
{
[Table("tblEmployees")]
public class Employee
{
[Key]
[Column(TypeName = "nvarchar")]
[StringLength(30)]
public string Id { get; set; }
[Column("First_Name")]
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
[Column(TypeName = "nvarchar")]
[StringLength(30)]
public string DepartmentId { get; set; }
[ForeignKey("DepartmentId")]
public Department Department { get; set; }
}
}
1, 在 初始化 DBcontext的时候 调用 context.SaveChanges();方法
在初始化器 中 通过 context.SaveChanges(); 来向数据库中填入一些初始数据。数据库中一开始并不存在sample数据库。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Entity;
namespace EntityFrameWorkDemo
{
public class CustomInitializer<T> : DropCreateDatabaseAlways<EmployeeDBContext>
{
public override void InitializeDatabase(EmployeeDBContext context)
{
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction
, string.Format("ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", context.Database.Connection.Database));
base.InitializeDatabase(context);
}
protected override void Seed(EmployeeDBContext context)
{
// Seed code goes here...
base.Seed(context);
}
}
public class DeleteAndCreateCustomInitializer<T>: IDatabaseInitializer<EmployeeDBContext>
{
public void InitializeDatabase(EmployeeDBContext context)
{
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction
, string.Format("ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", context.Database.Connection.Database));
context.Database.Delete();
context.Database.Create();
context.Departments.Add(new Department() {Name = "IT", Location= "New York" });
context.Departments.Add(new Department() { Name = "HR", Location = "London" });
context.Departments.Add(new Department() { Name = "payroll", Location = "sydney" });
context.Departments.Add(new Department() { Name = "SupplyChain", Location = "sini" });
context.Departments.Add(new Department() { Name = "Reporitory", Location = "tokio" });
context.Employees.Add(new Employee() { FirstName = "york5", LastName = "sun5", Gender = "male", Salary = 3000, DepartmentId = 1 });
context.Employees.Add(new Employee() { FirstName = "york1", LastName = "sun1", Gender = "female", Salary = 5800, DepartmentId = 2 });
context.Employees.Add(new Employee() { FirstName = "york2", LastName = "sun2", Gender = "male", Salary = 3000, DepartmentId = 3 });
context.Employees.Add(new Employee() { FirstName = "york3", LastName = "sun3", Gender = "female", Salary = 3900, DepartmentId = 1 });
context.Employees.Add(new Employee() { FirstName = "york4", LastName = "sun4", Gender = "male", Salary = 3000, DepartmentId = 2 });
context.SaveChanges();
}
}
public class EmployeeDBContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
public EmployeeDBContext() : base("EmployeeDBContext")
{
Database.SetInitializer<EmployeeDBContext>(new CustomInitializer<EmployeeDBContext>()); //Default one
}
}
}
如下,就是 EmployeeRepository类会绑定到一个asp.net 前端的ObjectSource ,执行,就会向数据库中插入数据。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Threading;
namespace EntityFrameWorkDemo
{
public class EmployeeRepository
{
public List<Department> GetDepartments()
{
//using (var context = new EmployeeDBContextFluentAPIContext())
//{
// Database.SetInitializer<EmployeeDBContextFluentAPIContext>(new CustomInitializer<EmployeeDBContext>());
// Student student = new Student()
// {
// StudentName = "梦缘",
// Age = 15,
// Sex = "男",
// Grade = "三年级"
// };
// context.Entry(student).State = System.Data.Entity.EntityState.Added;
// // 保存
// context.SaveChanges();
//}
//Thread.Sleep(500);
//Thread.Sleep(500);
//List<Department> ss = new List<Department>
//{
//};
//return ss;
EmployeeDBContext employeeDBContext = new EmployeeDBContext();
Database.SetInitializer<EmployeeDBContext>(new DeleteAndCreateCustomInitializer<EmployeeDBContext>());
return employeeDBContext.Departments.Include("Employees").ToList();
}
}
}
2, 使用 Database Migration ,在Configuration 类的Seed()方法中添加 新增数据指令。
这有一个好处,就是你只需要输入命令,而不用通过前台调用方法 来激发 数据初始化的工作。这种方法比较适合数据库不能随便删除重建。我们依然然让数据库 中不存在 Sample数据库。
在nuget程序包管理控制台 中 输入:Enable-Migrations
,这个指令 会在项目中加入Migrations/Configurations.cs文件。
namespace EntityFrameWorkDemo.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<EntityFrameWorkDemo.EmployeeDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(EntityFrameWorkDemo.EmployeeDBContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
}
}
}
以上这个类的代码会在执行Update-Database
指令的时候自动调用。我们是可以在Seed()方法中加入新增数据的指令。
namespace EntityFrameWorkDemo.CreateMigrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<EntityFrameWorkDemo.EmployeeDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"CreateMigrations";
}
protected override void Seed(EntityFrameWorkDemo.EmployeeDBContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
context.Departments.AddOrUpdate(c => c.Id,
new Department() { Id = "1", Name = "IT", Location = "New York" },
new Department() { Id = "2", Name = "HR", Location = "London" },
new Department() { Id = "3", Name = "payroll", Location = "sydney" },
new Department() { Id = "4", Name = "SupplyChain", Location = "sini" },
new Department() { Id = "5", Name = "Reporitory", Location = "tokio" }
);
context.Employees.AddOrUpdate(c => c.Id,
new Employee() { Id = "1", FirstName = "york5", LastName = "sun5", Gender = "male", Salary = 3000, DepartmentId = "1" },
new Employee() { Id = "2", FirstName = "york1", LastName = "sun1", Gender = "female", Salary = 5800, DepartmentId = "2" },
new Employee() { Id = "3", FirstName = "york2", LastName = "sun2", Gender = "male", Salary = 3000, DepartmentId = "3" },
new Employee() { Id = "4", FirstName = "york3", LastName = "sun3", Gender = "female", Salary = 3900, DepartmentId = "1" },
new Employee() { Id = "5", FirstName = "york4", LastName = "sun4", Gender = "male", Salary = 3000, DepartmentId = "2" }
);
}
}
}
一头小驴
发布了30 篇原创文章 · 获赞 3 · 访问量 1万+
私信
关注