private static Author CreateOrLoadAuthor(BookstoreEntities dbContext, string authorName) { Author existingAuthor = dbContext.Authors.Where(a => a.Name == authorName.ToLower()).FirstOrDefault(); if (existingAuthor != null) { return existingAuthor; } else { Author newAuthor = new Author() { Name = authorName.ToLower() }; dbContext.Authors.Add(newAuthor); dbContext.SaveChanges(); return newAuthor; } }
private static List<Author> GetOrCreateAuthors(ICollection<Author> authors, BookstoreDbContext bookstoreDb) { if (authors == null || authors.Count == 0) { return null; } var authorsInContext = new List<Author>(); foreach (var author in authors) { var addedAuthor = bookstoreDb.Authors .FirstOrDefault(a => a.Name.ToLower() == author.Name.ToLower()); if (addedAuthor != null) { authorsInContext.Add(addedAuthor); } else { var newAuthor = new Author { Name = author.Name, }; bookstoreDb.Authors.Add(newAuthor); authorsInContext.Add(newAuthor); bookstoreDb.SaveChanges(); } } return authorsInContext; }