entity framework 开始运行时向数据库中填入一些初始数据

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值