[Programming Entity Framework] Chapter 3rd querying the Entity Data Model (EDM) (i)

Source: Internet
Author: User

Http://www.cnblogs.com/sansi/archive/2012/10/18/2729337.html

Programming Entity Framework Second Edition translation index

You can query the Entity Data model using various methods. You choose some methods because of your personal preferences, while others are because you can take advantage of special benefits. You've probably heard LINQ to Entities and entity SQL. You can use special methods to query, such as some LINQ-based, and other EF-based objectquery classes. Each of these query methods will produce materialized objects. There is also a relatively few known query methods that use EF's EntityClient API, which allows data to be returned to the application in the form of data streams.

In this chapter, you will have the opportunity to try out all these different ways of querying. You will use a different mechanism to repeat some simple queries, and by looking at the results you can see the difference between these query methods.

At the end of this chapter, you will get a high-level understanding of all the query options and their basic use. In subsequent chapters, you can write more complex queries, and the basics you learn in this chapter will make that task easier. Also, at the end of this chapter you will see a key course for query execution.

Although the query examples in this chapter are presented in a console program, you can use LINQPad to test these queries and view the results. Some of the guidance in this chapter will also refer to debugging, which cannot be done in LINQPad. See the sidebar "LINQPad" on page 56th for more information on this tool.

Querying the model, not the database

In this chapter, you'll learn how to construct a query for the EDM created in chapter 2nd, and you'll learn to let EF handle it. Here you will experience the difference between writing queries against a data model and writing queries against a database. EF will process your query and use the ADO provider (here is System.Data.SqlClient) to turn the EDM query into a query that the target database can understand. After the database executes the query, the results are loaded into the objects that are generated based on the entity in the model.

These returned objects are a very important part of query processing, and of course you want to start querying, so first we look at it and then peek at the behind the scenes.

Your first EDM query

In the 2nd chapter, you create an EDM in a console program. Now you will create your first query with this EDM. You can use the same project, so if you close it, open it and we're about to start. The code in this section performs the simplest form of querying, which returns each contact entity for the database, and then displays the results in the console window.

    1. Open the Program.cs file.
    2. Add the methods in example 3-1 below the main method. When you write a query, the IntelliSense will remind you when you knock, which can speed up the writing of the Code.

      Example 3-1. Querying Contacts and writing out their names

Private static void Querycontacts ()

{

using (var context = new sampleentities ())

{

var contacts = context. Contact;

foreach (var contact in contacts)

{

Console.WriteLine ("{0} {1}", contact. Firstname.trim (), contact. Lastname.trim ());

}

}

Console.Write ("Press Enter ...");

console.readline ();

}

    1. Add the following code to the Main method:

Querycontacts ();

    1. Press F5 to run this code. When the code reads the ReadLine () method, all the names are listed in the console window.
    2. Press ENTER to run the program.

Now, let's run the query again, but this time we'll see what's going on.

    1. Set a breakpoint at the end of the foreach block, just close the curly brace.
    2. Press F5 to run the code again.
    3. When the debugger reaches the breakpoint, position the mouse pointer over the variable contact in the foreach statement, and you will see that it is a contact entity type, see Figure 3-1.

    1. Next, position the mouse pointer over the contacts variable of the same statement, and you see that it is the System.Data.Objects.ObjectSet of the contacts type. System.Data.Objects is an API that EF uses to create and manage entity objects. Objectset is returned by EF when accessing EntitySet (for example, contacts). It inherits from another class called ObjectQuery, and ObjectQuery is used to organize and execute queries that return objects. Once ObjectQuery is executed, it contains the results of the contact list data you see in the console. The context gets the returned data and uses it to generate these contact objects for you.

      Because only contacts is queried, and no filter is used, all contacts are removed from the database when the query is executed.

      Although this does not look like a query, it is indeed a query, albeit very simple. You'll learn more about it in the next query.

    2. You can continue to run the application or press the SHIFT+F5 key to stop it.

Now that you know this query returns OBJECTSET, you can rewrite the code to use the type declaration type that is displayed. In this way, you can use the code (for example, context. Contacts) There is no examine that specifies the type when the return type is displayed, which allows you or others to better understand the code later.

objectset<contact> contacts = context. Contacts;

Note: Objectset is under the System.Data.Objects namespace. Either specify it in the line of code, or you can increase the namespace at the beginning of the code file, C # with using System.Data.Object, or VB with the Imports System.Data.Objects.

Where do the contexts and classes come from?

Now that you've entered the code, there's definitely some doubt. For example, where does the contact type come from? How do I get a. NET strongly typed object from an XML file? Why context. Contacts is its own query, and what is the context?

One of the features of the EDM design tool is that the designer automatically executes code generation based on the model. The model's Designer.cs file is appended to the model in Solution Manager, as shown in 3-1.

In Solution Manager, expand the. edmx file to view the generated code file, open the file and see what's in it.

Note: Because the file is automatically generated, you do not edit it directly. You will learn how to customize the classes in this file in the 11th chapter.

The generator reads the conceptual layer in the model, then creates an EntityContainer-based ObjectContext from it, and then creates an entity class for each entity in the model. 3-3.

The generated code file contains four classes. Figure 3-4 shows these classes in the class Design view of VS. You can open a class in Class Designer and select View class diagram by right-clicking the class in Solution manager.

In the default view, click the top right corner to expand the first class that is sampleentities. This class takes the EntityContainer name of the model. The others are each entity, address,contact and vofficeaddresses.

ObjectContext class, Smapleentities

When you look at the XML view of the model in the 2nd chapter, you see EntityContainer that contain EntitySets and associationssets.

The Sampleentities class represents the EntityContainer, which inherits from the type ObjectContext of EF. This is why the variable context is used in the example. Asmpleentities has three properties, Addresses, Contacts, and vofficeaddresses, which are entitysets defined in the model. The three addto methods created by code generation provide the means to the context of new object instances, and then they are inserted into the database. These addto methods are intended for backwards compatibility with the EF version in. NET 3.5. In. NET 4, you should use the Add method provided by Objectset, which will be learned in later chapters.

Note: My habit is to use "context" as the variable name for the ObjectContext instance when writing code using EF.

Take a closer look at the Contacts property, and you see that it returns the contact type of Objectset:

Public objectset<contact> Contacts

Note: For VB developers, if you are not familiar with the syntax of generics, C # uses a sharp registered expression type, and VB uses the form plus keyword of. The preceding code uses VB to look like this:

Public Property Contacts as ObjectSet (of the contact)

The basis of our query is objectset, whether or not you want to query all the contact entities as in example 3-1, or you will request a subset as you would in the 3-2 example. Writing a query for Objectset is the same as a database query that writes database-based tables.

Entity class

The three entities defined in the model are the source of three entity classes. Each class inherits from the Entityobject of EF and contains properties based on the properties defined in the model, including contact.addresses and Address.contact navigation properties, if necessary. See Figure 3-5

But there's something new in the address class: Contactreference, which is another way to access the contact property. You will learn the details of the EntityReference attribute in the 19th chapter. These classes have more members, but they are not relevant to the queries made in this chapter, and we'll explain them in more detail in subsequent chapters of this book.

In-depth understanding: Don't be afraid to parse the generated code files in depth, but remember that any changes you make can rewrite the model at any time to modify and save.

Querying using LINQ to Entities

LINQ to Entities query syntax is easier to learn and use than Entitysql, and if you have used LINQ elsewhere, you may already be familiar with it. LINQ to Entities can meet most of your query needs.

LINQ is increased in. NET 3.5 when added to the language of VB and C #. LINQ represents the language INtegrated query,linq to entities is an implementation of it.

Note: Although F # itself does not support LINQ, the F # Add-on package created by the F # team provides LINQ queries.

Note: LINQ was originally written to provide a separate query language in all CLR objects. Now it has a lot of implementations. You just used an implementation to work with the entity object. The VS and. Net runtimes also contain LINQ to SQL, a query implementation that faces the SQL Server database directly. Many third-party vendors have written LINQ providers.

With LINQ queries you get a lot of creation, and it's easy to find lots of books about LINQR. When you begin to learn it, it is very helpful to understand the most basic structure.

Write your first LINQ to Entities query

The query mentioned earlier uses a shortcut to provide a query. But it's not like a real query. You will now write a LINQ to Entities query using the LINQ operator.

Remove the breakpoint from your previous step. On the line of code that creates the contacts memory variable, replace the context with the query in the 3-2 example. Contacts, which acquires a subset of the Contacts.

Example 3-2. A LINQ to Entities query in VB and C #

var contacts = from C in context. Contact

where c.firstname = = "Rebort"

select C;

Note: When writing a LINQ query, you will find a difference between VB and C # syntax. In addition to the case, note that VB does not display a requirement to use the Select operator, and C # must be used.

Run the program again and you'll see that only a small fraction of the contacts are listed, and their first name is Robert.

The most obvious sign of integration into a LINQ query is that IntelliSense provides help when you tap your query. For example, provide optional FirstName for variable C. That's because when you specify contacts at the beginning of a query, the compiler can determine that the item in that collection is the contact item. When you knock C at the back of the Select and where clauses, IntelliSense can list the properties of the contact that it suggests.

Why does LINQ start from?

The LINQ query starts from the FROM clause, not from the SELECT clause of another query language that we know well. When LINQ is created, the query statement does start with the SELECT clause. However, Microsoft's developers quickly realized that identifying the type being used enabled IntelliSense to provide more meaningful advice in the remaining queries.

Y.alan Griver, a member of Microsoft's early engagement with LINQ, revealed that when Microsoft's developers modified the syntax for IntelliSense, they joked that the syntax was "Yoda speak".

In the query, C is just any variable name, allowing you to reference what you need after the query. It is called a control variable. Control variables provide another way for IntelliSense and compilation to make LINQ more efficient for developers.

LINQPad

LINQPad is by O ' Reilly author, Joseph Albahari (He has works: LINQ Pocket Reference [http://oreilly.com/catalog/9780596519254/], C # 4.0 in A nutshell[http://oreilly.com/catalog/9780596800963/] and so on) written by powerful tools. It was originally written to use LINQ to Objects, but later, Joseph added support for LINQ to SQL and EF (Entity SQL and LINQ to Entities). It is a great way to test queries outside of your application.

[Programming Entity Framework] Chapter 3rd querying the Entity Data Model (EDM) (i)

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.