Entity Framework additions and deletions

Source: Internet
Author: User

Here I'm talking about the introduction to the Entity Framework. Download the Northwind database from the Web, create a new console program, and re-add an ADO Entity Data model.

"Gateway" (Operation context) for manipulating databases in EF

DbContext encapsulates the connection between the. NET Framework and the database. This class is used as a gateway for Create, read, update, and delete operations.
The DBContext class is used as the primary class for interacting with data as objects that are instances of the entity types defined in the EDM.
An instance of the DBContext class encapsulates the following:

    • A connection to the database, encapsulated as a EntityConnection object.
    • Describes the metadata of the model, encapsulated as a MetadataWorkspace object
    • Objectstatemanager object for managing persisted objects in the cache
First, the new
        #regionAdded 1.0Static intAdd () {Customers _customers=NewCustomers {customerid="Zhang", address="Luoyang West Street", city="Luoyang", phone="1314520",
Companyname="Microsoft", contactname="John Doe" }; //Method One//db. Customers.add (_customers); //Method TwoDbentityentry<customers> entry = db. Entry<customers>(_customers); Entry. State=System.Data.EntityState.Added; returndb. SaveChanges (); } #endregion
Second, simple query delay loading

To view deferred loading, use SQLProfiler to trace SQL statements

The EF generated SQL statements are sent to the database execution and can be viewed using SQL Server's Trace monitoring tool. (Can monitor SQL statements, CPU usage, execution time, etc.)

"Delay loading" is considered as two kinds:

1, the EF itself Query method returned is the IQueryable interface, the database is not queried at this time, only when the calling interface method to obtain data, the database is queried

2, "Delay loading", one of the essential reasons: the current may be through multiple Sqo methods to combine the query criteria, then each method is simply adding a query condition, can not determine whether this query condition has been added end so, there is no way to determine the time of each Sqo method SQL statement is what, can only return a A Dbquery object that contains all the added conditions, and when the Dbquery object is used, SQL statements are generated based on all conditions, querying the database

        #region2.1 Simple query Lazy load-void querydelay_01 ()Static voidquerydelay_01 () {dbquery<Customers> dbquery = db. Customers.where (U = u.contactname = ="Jacky Cheung"). (U = u.contactname). Take (2)

asSystem.data.entity.infrastructure.dbquery<customers>; //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 ~~! Customers Usr01 = Dbquery.firstordefault ();//ToList () ...Console.WriteLine (Usr01. ContactName); } //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 voidquerydelay_02 () {IQueryable<Orders> _orders = db. Orders.where (A = A.customerid = ="Tomsp");//true returned Dbquery object, returned as an interface//A. Only the Address table is queried at this timeOrders order =_orders.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 entityConsole.WriteLine (Order. Customers.contactname); //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<orders> orderlist =db. Orders; foreach(Orders oinchorderlist) {Console.WriteLine (O.orderid+": Contactname="+o.customers.contactname); } } #endregion
Third, modify
        #region3.0 Official Recommended modification method (check first, then modify)/// <summary>        ///3.0 Official Recommended modification method (check first, then modify)/// </summary>        Static voidEdit () {//1. Query for an object to be modified-Note: A proxy class object (wrapper class object) for the customers class is returned at this timeCustomers _customers = db. Customers.where (U = u.customerid = ="Zhang").            FirstOrDefault (); Console.WriteLine ("Before modification:"+_customers.contactname); //2. Modify the Content-Note: This is actually the properties of the proxy class object, which will set the value to the internal customers object corresponding to the property, while marking this property as the modified state_customers.contactname ="Andy Lau"; //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 ("Modification succeeded:");        Console.WriteLine (_customers.contactname); }        #endregion        #region3.1 Self-Optimizing modification method (Create object, modify directly)/// <summary>        ///3.1 Self-Optimizing modification method (Create object, modify directly)/// </summary>        Static voidEdit2 () {//1. Query for an object to modifyCustomers _customers =NewCustomers () {CustomerID ="Zhang", Address ="Luoyang West Street", City ="Luoyang", Phone ="1314520",
CompanyName ="Microsoft", ContactName ="Jacky Cheung" }; //2. Add the object to the EF container and get the state management object for the current entity objectDbentityentry<customers> entry = db. Entry<customers>(_customers); //3. Set the object to be modifiedEntry. State =System.Data.EntityState.Unchanged; //4. Set the ContactName property of the object to the modified state while entry. State is modified to Modified statusEntry. Property ("ContactName"). IsModified =true; //var u = db. Customers.attach (_customers); //u.contactname = "Aaron Kwok"; //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 statementdb. SaveChanges (); Console.WriteLine ("Modification succeeded:"); Console.WriteLine (_customers.contactname); } #endregion
Iv. deletion
        #region4.0 Delete-void Delete ()/// <summary>        ///4.0 Delete/// </summary>        Static voidDelete () {//4.1 Creating an object to deleteCustomers U =NewCustomers () {CustomerID ="Zhang" }; //4.2 Attaching to EFdb.            Customers.attach (U); //4.3 mark for deletion Note: This method is the mark of the current object as deleted state! db.            Customers.remove (U); /*You can also use Entry to attach and modify dbentityentry<customers> Entry = db.                entry<customers> (U); Entry.             state = System.Data.EntityState.Deleted; */            //4.4 Performing a Delete SQLdb.            SaveChanges (); Console.WriteLine ("Delete Success ~ ~ ~"); }        #endregion
V. Batch Processing
        #region5.0 batches--the benefits of the context SaveChanges Method!!!!/// <summary>        ///batching--the benefits of the context SaveChanges Method!!!! /// </summary>        Static voidsavebatched () {//5.1 New DataCustomers _customers =NewCustomers {CustomerID ="to ;", Address ="Luoyang West Street", City ="Luoyang", Phone ="1314520",
CompanyName ="Microsoft", ContactName ="Shanyujie" }; Db. Customers.add (_customers); //5.2 Add a second dataCustomers _customers2 =NewCustomers {CustomerID ="Zhao", Address ="Luoyang West Street", City ="Luoyang", Phone ="1314520",
CompanyName ="Microsoft", ContactName ="Zhao Kuangyin" }; Db. Customers.add (_CUSTOMERS2); //5.3 Modifying DataCustomers usr =NewCustomers () {CustomerID ="Zhao", ContactName ="Zhaomu" }; Dbentityentry<Customers> entry = db. Entry<customers>(USR); Entry. State=System.Data.EntityState.Unchanged; Entry. Property ("ContactName"). IsModified =true; //5.4 Deleting DataCustomers U =NewCustomers () {CustomerID ="Zou" }; //4.2 Attaching to EFdb. Customers.attach (U); //4.3 mark for deletion Note: This method is the mark of the current object as deleted state! db. Customers.remove (U); Db. SaveChanges (); Console.WriteLine ("Batch Completion ~~~~~~~~~~~~! "); } #endregion #region5.1 Batches--Add 50 data at a time-void Batcheadd ()/// <summary> ///5.1 Batch Processing--add 50 data at a time/// </summary> Static voidBatcheadd () { for(inti =0; I < -; i++) {Customers _customers=NewCustomers {CustomerID ="Zou"+ I, Address ="Luoyang West Street", City ="Luoyang", Phone ="1314520",
CompanyName ="Microsoft", ContactName ="Shanyujie"+i}; Db. Customers.add (_customers); } db. SaveChanges (); } #endregion

Entity Framework additions and deletions

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.