Build model
There are two ways to query EF, a LINQ query, a lambda expression
// Common Query Linq mode from in Db. Set<book>() where53 select b; // Normal query Lambda mode Iqueryable<book> List1 = db. Set<book>() 53);
//Multi-table query Linq varList = fromBookinchDb. Set<book>() Join BookTypeinchDb. Set<booktype>() on book. TypeId equals Booktype.typeidSelect New{book}; //Multi-table query lambda varList = db. Set<book>() . Where (U= U.bookid >2&& U.typeid = =4) . Join (db. Set<BookType> (), book = Book. TYPEID, TP = TP. TypeId, (book, TP) =New{book, TP});
//Query database only when deferred load is used .iqueryable<book> list = db. Set<book>() . OrderByDescending (U= U.bookid)//The expression method in the IQueryable object converts the lambda expression to an expression object by default. Skip (2) . Take (3); //no delay loading because IEnumerable has no way to stitch up full SQL statementsIenumerable<book> List1 = db. Set<book>() . AsEnumerable ()//Turn the result into a IEnumerable type. OrderByDescending (U =u.bookid). Skip (2) . Take (3);
Add data
[HttpPost] PublicActionResult Add (book book) {DbContext db=NewDbmodel (); Db. Set<Book>(). ADD (book); //returns the number of rows affected if(Db. SaveChanges () >0) { returnJson (New{msg="Add Success" }); }Else { returnJson (New{msg="Add failed" }); } }
modifying data
[HttpPost] public actionresult Edit (book BB) { new Dbmodel (); // Attach the object to the context state set to not change the db. Set<book>(). Attach (BB); = entitystate.modified; Db. SaveChanges (); return Json (new { " modified successfully " });
Delete data
Public ActionResult Delete (int ID) { new Dbmodel (); = db. Set<book> (). FirstOrDefault (b = B.bookid = = ID); Db. Set<Book>(). Remove (book); Db. SaveChanges (); return Json (new { " Delete succeeded " }, jsonrequestbehavior.allowget); }
Basic usage methods for the. NET Entity Framework