What is the difference between the approaches the addition/outcome of entities in EF



  • There's a contempor from the presentation that accepts the object of Class Book. db in this case context. As far as I'm concerned, the record can be done in two ways.

    First:

        public ActionResult Create(Book newBook)
        {
            db.Entry(newBook).State = EntityState.Added;
            db.SaveChanges();
        }
    

    And the other:

    public ActionResult Create(Book newBook)
        {
            db.Books.Add(newBook);
            db.SaveChanges();
        }
    

    Please tell me what the different approaches are and which one is preferable to use?



  • Specifically, there is no difference. It's preferable to use the one you understand personally.


    But in general, surgery. db.Books.Add(newBook); and db.Entry(newBook).State = EntityState.Added; They can behave differently.

    Method db.Books.Add(newBook); He'll check that newBook not yet added in the context db♪ If you download the book from the base, then add it back, there's a mistake.

    At the same time, db.Entry(newBook).State = EntityState.Added; Nothing checks out. If you download the book from the base, then add it back, it'll be a copy of the database.


    I don't see you having a db variable. I hope she's not static? The statistical context of EF is a serious mistake.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2