//создать файл с данными public void CreateJsonData(StoreSavedData data, string fileName = "data") { string json = JsonConvert.SerializeObject(data); using (StreamWriter writer = File.CreateText($"Files\\SavedData\\{fileName}.json")) { writer.Write(json); } }
public void SeedDataFromFile(StoreDbContext dataContext) { string categoryJson = GetDataFromJson("savedData"); StoreSavedData data = JsonConvert.DeserializeObject <StoreSavedData>(categoryJson); Dictionary <long, long> parentIds = new Dictionary <long, long>(); Dictionary <long, long> categoriesIds = new Dictionary <long, long>(); Dictionary <long, long> publishersIds = new Dictionary <long, long>(); List <long> oldCategoriesIds = new List <long>(); List <long> oldPublishersIds = new List <long>(); data.ParentCategories.ForEach((Category p) => { long oldId = p.Id; p.Id = 0; dataContext.Categories.Add(p); dataContext.SaveChanges(); parentIds.Add(oldId, p.Id); }); data.Categories.ForEach(c => { c.ParentCategoryID = parentIds[c.ParentCategoryID.Value]; oldCategoriesIds.Add(c.Id); c.Id = 0; dataContext.Categories.Add(c); }); dataContext.SaveChanges(); for (int i = 0; i < data.Categories.Count; i++) { categoriesIds.Add(oldCategoriesIds[i], data.Categories[i].Id); } data.Publishers.ForEach(p => { oldPublishersIds.Add(p.Id); p.Id = 0; dataContext.Publishers.Add(p); }); dataContext.SaveChanges(); for (int i = 0; i < data.Publishers.Count; i++) { publishersIds.Add(oldPublishersIds[i], data.Publishers[i].Id); } data.Books.ForEach(b => { b.CategoryID = categoriesIds[b.CategoryID.Value]; b.PublisherID = publishersIds[b.PublisherID.Value]; }); dataContext.Books.AddRange(data.Books); }
public string SaveDataToJson() { IQueryable <Book> dbbooks = _bookRepo.GetEntities().OrderBy(b => b.Id); IQueryable <Category> dbparents = _categoryRepo.GetEntities() .Where(p => p.ParentCategoryID == null).OrderBy(p => p.Id); IQueryable <Category> dbcategories = _categoryRepo.GetEntities() .Where(c => c.ParentCategoryID != null).OrderBy(c => c.Id); IQueryable <Publisher> dbpublishers = _publisherRepo.GetEntities().OrderBy(p => p.Id); StoreSavedData storeSavedData = new StoreSavedData { Books = dbbooks.ToList(), ParentCategories = dbparents.ToList(), Categories = dbcategories.ToList(), Publishers = dbpublishers.ToList() }; storeSavedData.Books.ForEach(b => { b.Id = 0; b.Category = null; b.Publisher = null; }); storeSavedData.ParentCategories.ForEach(p => { p.Books = null; p.ChildrenCategories = null; }); storeSavedData.Categories.ForEach(c => { c.ParentCategory = null; c.ChildrenCategories = null; c.Books = null; }); storeSavedData.Publishers.ForEach(p => p.Books = null); DataRW dataRW = new DataRW(); string msg = string.Empty; try { dataRW.CreateJsonData(storeSavedData, "savedData"); msg = "Данные сохранены в файл"; } catch (Exception ex) { msg = ex.Message; } return(msg); }