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.