Entity Framework Learning Advanced 1-Methods to improve the EF code (Part One)

Source: Internet
Author: User

In this section, we'll introduce some ways to improve the EF code, such as Notracking,getobjectbykey, include, and more.

L mergeoption.notracking

When we only need to read some data and do not need to delete, update, we can specify the way to use mergeoption.notracking to execute a read-only query (the EF default method is AppendOnly). When you specify that a read-only query is used with notracking, the reference entities associated with the entity are not returned and are automatically set to null. Therefore, using notracking can improve the performance of the query. The sample code is as follows:

[Test]

public void NoTrackingTest()

{

using (var db = new NorthwindEntities1())

{

//针对Customers查询将使用MergeOption.NoTracking

db.Customers.MergeOption = MergeOption.NoTracking;

var cust = db.Customers.Where(c => c.City == "London");

foreach (var c in cust)

Console.WriteLine(c.CustomerID);

//也可以这样写

//var cust1 = ((ObjectQuery<Customers>)cust).Execute(MergeOption.NoTracking);

//Esql写法

//string esql = "select value c from customers as c where c.CustomerID='ALFKI'";

//db.CreateQuery<Customers>(esql ).Execute(MergeOption.NoTracking).FirstOrDefault();

}

}

L Getobjectbykey/first

Getobjectbykey:

In EF, when you use the Getobjectbykey method to get data, it first queries whether there is a cache, and returns the required entity from the cache if there is a cache. If you do not query the database, return the entity that you want and add it in the cache for next use.

A: Always extract the required entities from the database.

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.