是否可以在实体框架中将种子数据导出为CSV?

时间:2017-06-02 19:06:25

标签: c# entity-framework csv

每次运行update-database时,我都希望将配置文件中的种子数据导出为CSV。我的配置文件很标准

public sealed class Configuration : Configuration<FooDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        CodeGenerator = new BaseMigrationCodeGenerator();
    }

    protected override void Seed(FooDbContext context)
    {
        FooSeed.AddSeed(context);
        context.SaveChanges();
    }
}

除了保存在数据库中之外,我想以CSV格式输出这些数据(包含在AddSeed中,包含在Foo对象列表中)。我对实体框架不够熟悉,不知道这是否可能,如果可行,怎么做?

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。在播种记录时,您可以同时将记录写入CSV。

参考以下内容:

https://www.tutorialspoint.com/entity_framework/entity_framework_seed_database.htm

public class MyContext : DbContext {

   public MyContext() : base("name=MyContextDB") {
      Database.SetInitializer<MyContext>(new UniDBInitializer<MyContext>());
   }

   public virtual DbSet<Course> Courses { get; set; }
   public virtual DbSet<Enrollment> Enrollments { get; set; }
   public virtual DbSet<Student> Students { get; set; }

   private class UniDBInitializer<T> : DropCreateDatabaseAlways<MyContext> {

      protected override void Seed(MyContext context) {

         IList<Student> students = new List<Student>();

         students.Add(new Student() {
            FirstMidName = "Andrew", 
            LastName = "Peters", 
            EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) 
         });

         students.Add(new Student() {
            FirstMidName = "Brice", 
            LastName = "Lambson", 
            EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
         });

         students.Add(new Student() {
            FirstMidName = "Rowan", 
            LastName = "Miller", 
            EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
         });

         foreach (Student student in students)
         context.Students.Add(student);
         // write to CSV
         WriteToCSV(Students);
         base.Seed(context);
      }

      private void WriteToCSV(Students students)
      {
        ...code to write to csv
      }
   }
}