public void Test() { var authors = new List<Author> { new Author { BirthDate = DateTime.Now, FirstName = "First Name" }, new Author { BirthDate = DateTime.Now, FirstName = "First Name 2" }, }; var books = new List<Book>(); authors.ForEach(x => { var book = new Book { Description = "Description " + x.AuthorId, AuthorId = x.AuthorId }; //db.Authors.Attach(x); //db.Entry(x).State = EntityState.Added; x.Books.Add(book); }); db.Authors.AddRange(authors); db.SaveChanges(); var id = authors.FirstOrDefault().AuthorId; }
public IHttpActionResult PostBook(Models.BooksModel.BooksModel booksModel) { if (!ModelState.IsValid) return BadRequest(ModelState); var book = new Book { Description = booksModel.Description, Title = booksModel.Title, PublishDate = booksModel.PublishDate }; try { db.Books.Add(book); db.SaveChanges(); return Created("DefaultApi", new { id = book.BookId }); } catch (Exception) { return StatusCode(HttpStatusCode.InternalServerError); } }