Entity FrameWork 5 Additions and deletions & call SQL statements directly?

Source: Internet
Author: User

#region 1.0 Add-void Add ()//<summary>///1.0 new//</summary>static void Add () {//1.1 Create entity object User Uobj = new User () {uName = "Andy Lau", Uloginname = "AAA", upwd = "ASDFASDFASDFSADF", Uisdel = False    , uaddtime = DateTime.Now}; 1.2 Add an object to the user collection in the data context by adding the EF to the database//1.2.1//db.    Users.add (Uobj); Dbentityentry<user> entry = db.    Entry<user> (Uobj); Entry.    state = System.Data.EntityState.Added; The 1.2.2 invokes the Save method of the data context, storing the object as a database of DB.    SaveChanges (); Console.WriteLine ("Save Successful ~~! ");} #endregion #region 2.0 Simple Query-void query ()///<summary>///2.0 Simple query///</summary>static void query () {//2.0 The SQO nature of IEnumerable (collection) and IQueryable (dbset<t> in EF) is different! : The standard query operator method for the//2.1 collection is the extension method that is added to the IEnumerable interface in System.Linq.Enumerable//list<string> liststr = new Li    St<string> (); The standard query operator method in the dbset<t> in the context of the Liststr.where//ef, from the extension added to the IQueryable interface in System.Linq.QueryableLaw//2.2 Instant query List<user> List = db. Users.where (U = u.uname = = "Andy Lau").    ToList (); List. ForEach (U = Console.WriteLine (u.tostring ()));} #endregion #region 2.1 Simple query delay load-void querydelay_01 ()//"lazy load" as two kinds://2.1 EF itself, the query method returned is the IQueryable interface, at this time did not query the database                          Only when the calling interface method gets the data, the database//2.1.1 "delay loading" is queried, one of the essential reasons: the query condition may be combined by multiple sqo methods, so each method simply adds a query condition and cannot determine whether the query condition has been added to the end/ Therefore, there is no way to determine what the SQL statement is at each Sqo method, and can only return a Dbquery object that contains all the added conditions,//When using this Dbquery object SQL statements are generated based on all conditions, querying the database static void Querydelay_01 () {dbquery<user> dbquery = db. Users.where (U = u.uloginname = = "Andy Lau"). (U = u.uname).    Take (2) as system.data.entity.infrastructure.dbquery<user>;    After obtaining the deferred query object, call the object to get the first data method, at this time, "will be based on the previous conditions", generate SQL statements, query the database ~~!    User Usr01 = Dbquery.firstordefault ();//ToList () ... Console.WriteLine (usr01.uloginname);} 2.1.2 "lazy load"-delay for foreign key entities (load on demand)! Two essential reasons: for foreign key properties, EF uses this foreign key attribute to query the corresponding table. Static void Querydelay_02 () {iqueryable<usersaddress> Addrs = db. Usersaddresses.where (A = A.uduid = = 1);//Real return Dbquery object, return//a as an interface. Only the Address table usersaddress Addr01 = Addrs is queried at this time.    FirstOrDefault (); B. When accessing the foreign key entity in the Address object, EF queries the user table for the address and, after the query, loads the data into the foreign key entity Console.WriteLine (Addr01.     User.uname); C. The disadvantage of "lazy loading" loading on demand: Every time a foreign key entity is called, the database is queried (EF has small optimizations: the same foreign key entity is checked only once) iqueryable<usersaddress> addrs2 = db.    usersaddresses; foreach (usersaddress add in Addrs2) {Console.WriteLine (add.udaddress + ": username=" + Add.)    User.uname); }} #endregion #region 2.2 connection query (generate INNER join)-void queryinnerjoin ()//<summary>///2.2 connection query (generate INNER JOIN)///</ summary>static void Queryinnerjoin () {///by using the Include method, when you set up EF to generate SQL statements, use the inner join to find out the user attribute corresponding to the Address table//Selec T * from Usersaddresses a inner joins Users u on a.udid =u.id iqueryable<usersaddress> Addrs = db. Usersaddresses.include ("User").    Where (A = A.udid = = 1); foreach (usersaddress add in Addrs)    {Console.WriteLine (add.udaddress + ": username=" + Add.)    User.uname); }//Practice: Query The message table at the same time, display the message sender and receive the name iqueryable<msg> msgs = db. Msgs.include ("User").    Include ("User1"); foreach (Msg m in msgs) {Console.WriteLine (M.mid + ", Sender:" + m.user.uname + ", Receiver:" + m.user1.uname + ", Message content:"    + m.mmsg); }} #endregion #region 3.0 official Recommended modification method (check first, then modify)///<summary>///3.0 official Recommended modification method (check first, then modify)///</summary>static void Edit () {//1. Query for an object to be modified-Note: A proxy class object (wrapper class object) of the user class is returned at this time, user USR = db. Users.where (U = u.uid = = 1).    FirstOrDefault (); Console.WriteLine ("Pre-modification:" + usr.)    ToString ());    2. Modify the Content-note: At this point, the action is the properties of the proxy class object, these properties, the value is set to the internal user object corresponding to the property, while marking this property as modified state Usr.uname = "Andy Lau";    Usr.uloginname = "Liudehua";    3. Re-save to database-Note: At this point, the EF context checks all objects inside the container, finds the object marked as modified, and then finds the object attributes marked as modified, generating the corresponding UPDATE statement execution! Db.    SaveChanges ();    Console.WriteLine ("Modified successfully:"); Console.WriteLine (usr. ToString ());} #endregion #region 3.1 Self-Optimizing modification method (create object, directly modify)///<summary>///3.1 own optimized modification method (create object, directly modify)///</summary>static void Edit2 () {//1. Query for an object to modify User usr = n    EW User () {uId = 8,uname= "Small white ~ ~ ~"}; 2. Add the object to the EF container and get the current entity object's state management Object dbentityentry<user> entry = db.    entry<user> (USR); 3. Set the object to be modified entry.    state = System.Data.EntityState.Unchanged; 4. Set the Uname property of the object to the modified state while entry. State is modified to Modified status entry. Property ("UName").     IsModified = true; var u = db.    Users.attach (USR);     U.uname = "Small white ~ ~"; 3. Resave to the database-the EF context is based on the state of the entity object, according to entry. The value of State =modified generates the corresponding update SQL statement db.    SaveChanges ();    Console.WriteLine ("Modified successfully:"); Console.WriteLine (usr. ToString ());} #endregion #region 4.0 Delete-void Delete ()//<summary>///4.0 Delete//</summary>static void Delete () {//4.1 Create to    deleted object User u = New User () {uId = 10}; 4.2 is attached to the DB in EF.    Users.attach (U);    4.3 Mark for deletion Note: This method is the mark of the current object as deleted state! Db.     Users.remove (U); /* You can also use Entry to attach and modify the DbEntityentry<user> entry = db.        entry<user> (U); Entry.     state = System.Data.EntityState.Deleted; *///4.4 Execute DELETE SQL db.    SaveChanges (); Console.WriteLine ("Delete Success ~ ~ ~");} #endregion #region 5.0 Batches--the benefits of the contextual SaveChanges approach!!!! <summary>///batching--the benefits of the contextual SaveChanges approach!!!! </summary>static void savebatched () {//5.1 new data user Uobj = New User () {uName = "Andy Lau", UL    Oginname = "AAA", upwd = "ASDFASDFASDFSADF", Uisdel = False, Uaddtime = DateTime.Now}; Db.     Users.add (Uobj); 5.2 Add a second data user UObj2 = New User () {uName = "Andy Lau 2", uloginname = "Aaa2", upwd = "asdfasdfasd    Fsadf2 ", Uisdel = False, Uaddtime = DateTime.Now}; Db.     Users.add (UOBJ2);    5.3 Modifying data user USR = new user () {uId = 8, UName = "Black again ~ ~ ~"}; Dbentityentry<user> entry = db.    entry<user> (USR); Entry.    state = System.Data.EntityState.Unchanged; Entry. Property ("UName"). Ismodified = true;    5.4 Delete data user U = New User () {uId = 11}; 4.2 is attached to the DB in EF.    Users.attach (U);    4.3 Mark for deletion Note: This method is the mark of the current object as deleted state! Db.     Users.remove (U); Db.    SaveChanges (); Console.WriteLine ("Batch Complete ~~~~~~~~~~~~! ");} #endregion #region 5.1 Batches--Add 50 data at a time-void batcheadd ()///<summary>///5.1 batch--add 50 data at a time//</summary>  static void Batcheadd () {for (int i = 0; i < i++) {User Uobj = new User () {uName =            "Andy Lau" + I, Uloginname = "AAA" + I, upwd = "ASDFASDFASDFSADF" + I, Uisdel = False,        Uaddtime = DateTime.Now}; Db.    Users.add (Uobj); } db. SaveChanges ();} #endregion

  

, and the method db that calls the SQL statement directly. Database.executesqlcommand ("");            Db. Database.sqlquery            //db. Database.sqlquery<t>

  

Entity FrameWork 5 Additions and deletions & call SQL statements directly?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.