Export data in C # / VB format for use in EF Code First Database Initialization

Several times, sample data is important, but boring to generate due to many related tables. So, in the Entity Framework Code, at first I think this is an elegant way to insert them into DropCreateDatabaseIfModelChanges :: Seed ().

But is there a way to export existing data from the database back to the row as C # / VB sentences that insert poco objects?

If this works, we can use it to back up data gracefully or save it in several scripted scenarios, switch them as needed to improve our test, etc.

EXPORT DATABASES AS NEXT CODE:

var students = new List<Student> { new Student { FirstMidName = "Carson", LastName = "Alexander", }, new Student { FirstMidName = "Meredith", LastName = "Alonso", }, new Student { FirstMidName = "Arturo", LastName = "Anand", }, // ... }; students.ForEach(s => context.Students.Add(s)); context.SaveChanges(); 
+8
database export entity-framework code-first
source share
1 answer

As @Luke suggested in his comment. The best way is to generate Json files for your seed data.

in this article , you can find an easy way to generate Json from an SQL query.

Then you only need to read them Newtonsoft.Json

eg.

 var countriesStream = new StreamReader(HostingEnvironment.MapPath("jsonFile.json")); try { countriesList = JsonConvert.DeserializeObject<List<Country>>(countriesStream.ReadToEnd()); } 
+1
source share

All Articles