简体   繁体   中英

Is it possible to export seed data to CSV in Entity Framework?

I would like to export my seed data in the configuration file to CSV every time I run update-database. My configuration file is pretty standard

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

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

I want to output this data (contained in AddSeed, a list of Foo objects) in CSV format, in addition to its being saved in the database. I'm not familiar enough with Entity Framework to know whether this is possible and if so, how?

Yes it is possible. When you are seeding records, you can simultaneously write the record to a CSV.

Referencing the following:

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
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM