EntityFramework A cursory walkthrough of the CRUD (UP)

Source: Internet
Author: User

For any ORM framework, CRUD is its core function, so to speak, the CRUD function to achieve good or bad, directly determine the fate of this ORM framework.

CRUD is English create, Read, Update, delete four words of the abbreviation, corresponding to Chinese, is "increase, delete, change, check" four words. Subdivide again, "Add, Delete, change" can be classified as a category, its characteristic is to update the data source, and "check" is classified as another category, it does not modify the original data source.

Our technology exploration journey begins with "check".

12 ways to query data

EF queries data primarily in two ways: linqto entities and a set of extension methods for iqueryable<t>.

Query code with LINQ is highly readable:

[CSharp]View Plaincopyprint?
    1. using   (var context = new  bookdb ())   
    2. {  
    3.      var books = from book incontext. books  
    4.     select new  {  Bookname = book. Name , reviewcount = book. reviews.count };  
    5.     foreach   (var book in  books)   
    6.      {  
    7.          Console.WriteLine (, book.bookname, book.reviewcount);   
    8.     }  
    9. }&NBSP;&NBSP;


Without commenting, just looking at the code makes it easy to know how much it functions to extract book reviews for all books stored in the database.

These functions can also be implemented using the extension method, when you need to write a lambda expression:


[CSharp]View Plaincopyprint?
    1. using (var context = new bookdb ())
    2. {
    3. foreach (Var book incontext. Books.select (b = new {bookname = b.name, Reviewcount = B.reviews.count}))
    4. {
    5. Console.WriteLine ("{0} has comment {1}. ", Book.bookname, Book.reviewcount);
    6. }
    7. }

These two ways are not good or bad, but using the second way may make others think you "compare cow B". :-)

2 Loading the associated data

Most data entities have a variety of associations, the most common being a book associated with multiple book reviews, which is a one-to-many association. The relationship between the book and the author of the book is a many-to-many association: an author can write more than one book, and a book author can be more than a.

EF establishes navigation properties between data entities to implement correlation. In a real project, it is often after you get one (or a bunch) of entity objects that you need to query the information encapsulated by the associated "Another Heap" object, which is the "loading of associated data" issue.

For this problem, EF supports three kinds of loading strategies.

(1) When the navigation property is virtual, EF uses lazy load (lazy loading)by default. For example, the relationship between books and book reviews is defined as follows:


[CSharp]View Plaincopyprint?
    1. Public class Book
    2. {
    3. ......
    4. Public Virtual List<bookreview> Reviews { get; set; }
    5. }

only when the reviews property of a book object needs to be accessed in the program does EF issue a SQL command to the database to load the relevant review data.

(2) If you confirm that the data associated with an entity object is really needed, you can use the Include () method to notify EF that the EF will tell the database: "Pack xxx and XXX and send it to me at once":

[CSharp]View Plaincopyprint?
    1. var books = from book in context. Books.include ("Reviews")
    2. Select Book;
    3. foreach (Var book in Books)
    4. {
    5. Console.WriteLine ("{0} has comment {1}. ", book. Name, book. Reviews.count);
    6. }

This is called " Pre-loading (Eager Loading)". Avoids the need to access the database for the 2nd time.

(3) The third way, called " Explicit loading (Explicit Loading)", is implemented using the load () method, for example, the following code lets EF load 50 books and book review information into memory:

[CSharp]View Plaincopyprint?
    1. Context. Books.take (50). Include ("Reviews"). Load ();

After the data is "in place", it can be cached for backup.

We can also only extract the required data "with purpose", see the following code:

[CSharp]View Plaincopyprint?
    1. using (var context = new bookdb ())
    2. {
    3. Book Book =context. Books.first ();
    4. Context. Entry (book). Collection ("Reviews"). Load ();
    5. Console.WriteLine ("{0} has review {1}".) ", book. Name, book. Reviews.count);
    6. }

The code above will only fetch all the book reviews from the first one.

Here is a summary of these three modes:

(1) In terms of query performance, is " pre-loaded (Eager Loading)" Best, because the data are all loaded into memory, subsequent queries no longer need to access the database. The disadvantage is that it can consume a lot of memory.

(2) If you can predict the data items to access, and the current data object in memory, only a few objects need to query for further data, then using the " explicit load (Explicit Loading)" policy can effectively reduce the amount of data transfer, to achieve higher performance.

(3) When an entity class has multiple one-to-many associations, and it is difficult to predict which data items to access, then "lazy Loading" is more appropriate, it only extracts data "when needed", which can effectively reduce memory consumption. However, it may cause too many requests for data queries to the database server.

(4) When a data entity object needs to be serialized, be sure to use " preload (Eager Loading)" because the object needs to be serialized using reflection to query all properties of the data entity object, if it is deferred (lazy Loading) , will cause a large number of query requests to the database, and each object to issue a "heap" of such query requests, will definitely make the database pain!

3 Find Method vs. local data

Dbset has a local property that is interesting in that it refers to data that is currently loaded into memory, noting that it includes data that is currently taken out of the database or newly added but not yet saved to the database, which we can refer to as the "local data collection" of the Dbset object.

An important feature of local data collections is that the various queries issued against it are not sent to the database.

Take a look at the following scenarios:

Assuming I only want to extract the book review information for the 1th and 11th books in the database, the following code accomplishes this:

[CSharp]View Plaincopyprint?
    1. using (var context = new bookdb ())
    2. {
    3. Book Book =context. Books.first ();
    4. Console.WriteLine ("{0} has review {1}".) ", book. Name, book. Reviews.count);
    5. Book =context. Books.orderby (b = b.bookid). Skip (10). First ();
    6. Console.WriteLine ("{0} has review {1}".) ", book. Name, book. Reviews.count);
    7. }


Open SQL Server Profiler and you'll notice that EF has generated 4 SQL commands for the above code to send to the database.

Now modify the code and use the explicit mount + Local query method:

[CSharp]View Plaincopyprint?
  1. using (var context =new bookdb ())
  2. {
  3. //Loading 50 books and book review data into memory in advance
  4. Context. Books.take (50). Include ("Reviews"). Load ();
  5. //query in a local collection
  6. Book Book =context. Books.Local.First ();
  7. Console.WriteLine ("{0} has review {1}".) ", book. Name, book. Reviews.count);
  8. Book =context. Books.Local.OrderBy (B=>b.bookid). Skip (10). First ();
  9. Console.WriteLine ("{0} has review {1}".) ", book. Name, book. Reviews.count);
  10. }


Looking at SQL Serverprofiler, you will find that EF only generates an SQL command for the above code (although this command is more complex, but only one) to the database, the subsequent queries are in memory, quite quickly!

The local data collection also has another feature that deserves attention.

Note that the type of the Dbset.local property is ObservableCollection, and this local data collection object fires the CollectionChanged event when data is added to and removed from Dbset. This is fantastic for WPF desktop applications!

You can do this in the WPF Desktop program:

After extracting the data using DbContext, the WPF data-bound control (such as the DataGrid) is bound to the local property of the corresponding Dbset through the Viewsource component, which can then be used for CRUD operations on the form, and all operations are dbcontext cached. When the user clicks the Save button (or closes the form), the Dbcontext.savechanges () method is called to deposit the database. DbContext automatically tracks the state of the entity object, and the whole process is completely automated!

If you are based on. NET 4.5 and Use EF 6, you can use EF6 's new async method directly in your WPF application, such as Dbcontext.savechangesasync (), where EF will perform the extraction, saving, etc. of the data in a separate thread (the task of assigning the thread to the underlying . NET TPL is responsible, the programmer can ignore it), and at the end of these work, the successor code of the Async method will be executed in the UI thread, so that the problem of the annoying cross-thread update UI control in the multithreaded application does not exist, it is convenient to use, the code can be streamlined a lot!

The last topic associated with the "Local data collection" is the Dbset Find method, which is developed with the following words in mind:

When querying data using the Find method, it is first found in memory, not found, and then fetched in the database.

There are a lot of tips on data query, this article just introduced I think the more important knowledge and some of the more useful skills, is a point.

The next article leads you to the "Update data" field of EF "Searching for a new one".


Source: >  

From for notes (Wiz)

EntityFramework A cursory walkthrough of the CRUD (UP)

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.