Ways to improve EF code (on)

Source: Internet
Author: User

In this section, we will introduce some methods to improve EF code, such as Notracking,getobjectbykey, include, and so on.

> mergeoption.notracking

When we only need to read some data without deleting or updating, we can specify how to execute a read-only query using mergeoption.notracking (the default way for EF is appendonly). When you specify to use notracking for a read-only query, entity-related reference entities are not returned, and they are automatically set to null. Therefore, using notracking can improve the performance of the query. The sample code is as follows:

 Public voidnotrackingtest () {using(vardb =NewNorthwindEntities1 ()) {    //queries for customers will use mergeoption.notrackingDb. Customers.mergeoption =mergeoption.notracking; varCust = db. Customers.where (c = c.city = ="London"); foreach(varCinchCust)    Console.WriteLine (C.customerid); //can also be written like this//var cust1 = ((objectquery<customers>) Cust).    Execute (mergeoption.notracking); //esql notation//String esql = "Select value c from Customers as C where c.customerid= ' ALFKI '"; //db. Createquery<customers> (ESQL). Execute (mergeoption.notracking). FirstOrDefault ();    }}

> Getobjectbykey/first

Getobjectbykey:
In EF, when you use the Getobjectbykey method to get data, it first queries for a cache and returns the required entities from the cache if there is a cache. If not, query the database, return the required entities, and add them in the cache for the next use.
First: Always extract the required entities from the database.
Therefore, we should choose the Getobjectbykey method in the appropriate place to obtain data to reduce access to the database to improve performance. The sample code is as follows:

 Public voidgetbykeytest () {using(vardb =NewNorthwindEntities1 ()) {    //extracting data from the database    varCST = db. Customers.first (c = C.customerid = ="ALFKI"); Console.WriteLine (CST.    CustomerID); //the data will be fetched from the cacheEntityKey key =NewEntityKey ("northwindentities1.customers","CustomerID","ALFKI"); varCst1 = db. Getobjectbykey (Key) asCustomers; Console.WriteLine (Cst1.   CustomerID); }}

Also, it is important to note that if Getobjectbykey does not get the data that meets the criteria, it throws an exception. To prevent this from happening, we should use the Trygetobjectbykey method where there is a possibility of an exception. The Trygetobjectbykey method obtains data in a similar way to Getobjectbykey, except that Trygetobjectbykey returns null instead of throwing an exception when no qualifying data is fetched. The sample code is as follows:

 Public voidtrygetbykeytest () {using(vardb =NewNorthwindEntities1 ()) {    //data that is not eligible will be thrown unexpectedlyEntityKey key =NewEntityKey ("northwindentities1.customers","CustomerID","Windmill car. Net"); varCST = db. Getobjectbykey (Key) asCustomers; Console.WriteLine (CST.    CustomerID); //data that does not meet the criteria will return nullEntityKey Key1 =NewEntityKey ("northwindentities1.customers","CustomerID","Windmill car. Net"); Object Cst1=NULL; Db. Trygetobjectbykey (Key1, outcst1); if(Cst1! =NULL) Console.WriteLine (((Customers) cst1).    CustomerID); }}

> First/firstordefault

First: When we use first to get the data, if there are no qualifying data, then our code throws an exception.
FirstOrDefault: When we use FirstOrDefault to get the data, if there is no qualifying data, then it will return null.
Obviously, for a good code, the predictable exception is handled, not waiting for it to be thrown out. The sample code is as follows:

 Public voidfirsttest () {using(vardb =NewNorthwindEntities1 ()) {    //exception-throwing code    varCST = db. Customers.first (c = C.customerid = ="Windmill car. Net"); Console.WriteLine (CST. CustomerID);//throws an exception here//the recommended use of the following code:    varCst1 = db. Customers.firstordefault (c = C.customerid = ="Windmill car. Net"); if(Cst1! =NULL) Console.WriteLine (Cst1.    CustomerID); }}

> Deferred load/include

EF does not support partial attribute lazy loading of an entity, but it supports lazy loading of entity relationships. By default, the relationship of an entity is not loaded. The following code:

 Public voidincludetest () {using(vardb =NewNorthwindEntities1 ()) {       varCSTs =db.    Customers; foreach(varCinchCSTs)        {Console.WriteLine (C.customerid); foreach(varOinchc.orders) Console.WriteLine ("   "+O.orderid); }    }}

In the above code, because orders is not loaded, there is no output when the orders are output.
When we need to load some associated relationships, we use the Include method, as shown in the following code:

 Public voidincludetest () {using(vardb =NewNorthwindEntities1 ()) {       varCSTs = db. Customers.include ("Orders"); foreach(varCinchCSTs)        {Console.WriteLine (C.customerid); foreach(varOinchc.orders) Console.WriteLine ("   "+O.orderid); }    }}

In the code above, orders associated with customers will be loaded.

> The entity that gets the primary key based on the foreign key

 Public Static void waijiantest () {    var stu = me. Student;     foreach (var in Stu)    {    Console.WriteLine (s.studentid);    Console.WriteLine (s.class.classname);    Console.WriteLine ("---------");}    }

Where class is the primary key class, ClassName is the property of the main key

Ways to improve EF code (on)

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.