public static List <Chapter> AddChapters(List <Chapter> chapters, int bookId) { var titles = chapters.Select(x => x.ChapterTitle).ToList(); using (var db = new SqliteDbContext()) { var oldChapters = db.Chapters.Where(x => x.BookId == bookId && titles.Contains(x.ChapterTitle)).ToList(); var id = db.Chapters.OrderByDescending(x => x.Id).FirstOrDefault()?.Id ?? 0; foreach (var item in chapters) { var oldBook = oldChapters.FirstOrDefault(x => x.ChapterTitle.Equals(item.ChapterTitle)) ?? new Chapter(); if (item.ChapterTitle.Equals(oldBook.ChapterTitle)) { continue; // 同名章节,跳过 } item.Id = ++id; db.Chapters.Add(item); } db.SaveChanges(); } return(chapters); }
public static Book AddBook(Book book) { using (var db = new SqliteDbContext()) { db.Database.EnsureCreated(); var oldBook = db.Books.Where(x => x.BookName.Equals(book.BookName) && x.Author.Equals(book.Author)).FirstOrDefault(); if (oldBook != null) { oldBook.CrawlerRuleName = book.CrawlerRuleName; oldBook.StartUrl = book.StartUrl; } else { var id = db.Books.OrderByDescending(x => x.Id).FirstOrDefault()?.Id ?? 0; book.Id = ++id; db.Books.Add(book); oldBook = book; } db.SaveChanges(); return(oldBook); } }