数据迁移一篇比较好的文章: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