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

Source: Internet
Author: User
ArticleDirectory
    • Where does the context and class come from?
    • Write your first LINQ to entities Query
Programming Entity FrameworkVersion 2Translation Index

You can use various methods to query the object data model. You choose some methods because of your personal preferences, while others because you can use special benefits. You may have heard of LINQ to entities and Entity SQL. You can use special methods to query, such as some objectquery classes based on LINQ and others based on EF. Each of these query methods generates a specific object. Another method that few people know is to use EF's entityclient API, which allows data to be returned to the application in the form of data streams.Program.

In this chapter, you will have the opportunity to try all these different query methods. You will use different mechanisms to repeat some simple queries. by viewing the results, you can see the differences between these query methods.

At the end of this chapter, you will have a high-level understanding of all query options and their basic usage. In subsequent chapters, you can write more complex queries. The basics you have learned in this chapter will make that task easier. In addition, you will see the key courses for query execution at the end of this chapter.

Although the query examples in this chapter are shown in the console program, you can use linqpad to test these queries and view the results. Some guidance in this chapter will also mention debugging, which cannot be done in linqpad. Click "linqpad" on the sidebar on the 56th page to view more information about this tool.

Query models, not Databases

In this chapter, you will learn how to construct a query for the EDM created in Chapter 2nd. You will learn how to let EF handle this issue. Here you will go through the difference between writing queries for data models and writing queries for databases. EF will process your query and use the ADO. net provider (here is system. Data. sqlclient) to convert the EDM Query into a query that can be understood by the target database. After the database executes the query, the results are loaded into objects generated based on the entity in the model.

These returned objects are a very important part of query processing. Of course, you want to start the query. First, let's query the objects and then peek at the background.

Your first EDM Query

In Chapter 2nd, you create an EDM instance in a console program. Now you create your first query for this EDM. You can use the same project, so if you close it, open it and we are about to begin. In this sectionCodeThe simplest Query Form is executed. It returns each contact entity of the database and then displays the result in the console window.

    1. Open the program. CS file.
    2. Add the method in Example 3-1 below the main method. When you write a query, smart sensing will remind you when you press. This will speed up code writing.

      Example 3-1. querying contacts and writing out their names

Private Static VoidQuerycontacts ()

{

Using(VaRContext =New Sampleentities())

{

VaRContacts = context. contact;

Foreach(VaRContactInContacts)

{

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 the code. When the Code reads the Readline () method, all names are listed in the console window.
    2. Press the Enter key to run the program.

Now we can run a query again, but this time we can see what happened.

    1. Set a breakpoint at the end of the foreach block, that is, close the braces.
    2. Press F5 to run the code again.
    3. When the debugger reaches the breakpoint, place the mouse pointer on the contact variable in the foreach statement. You will see that it is a contact entity type. See figure 3-1.

    1. Next, place the cursor over the contacts variable of the same statement. You can see that it is a contacts-type system. Data. Objects. objectset. System. Data. Objects is an API that EF uses to create and manage object objects. Objectset is returned by EF when you access entityset (such as contacts. It inherits from another class called objectquery. objectquery is used to organize and execute the query of returned objects. Once the objectquery is executed, it contains the contact list data results you can see on the console. Context obtains the returned data and uses it to generate these contact objects for you.

      Because only contacts is queried and no filtering conditions are used, all contacts are retrieved from the database when the query is executed.

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

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

Now you know that this query returns objectset. You can rewrite the code and use the displayed type declaration type. In this way, you can specify the type when the Code (for example, context. Contacts) does not explicitly display the returned type, which allows you or others to better understand the code in the future.

Objectset <contact> contacts = context. contacts;

Note: objectset is in the system. Data. Objects namespace. You can also specify it in the code line, or add a namespace at the beginning of the code file. C # uses using system. Data. object, or vB uses imports system. Data. Objects.

Where does the context and class come from?

Now that you have entered the code, you will certainly have some questions. For example, where does the contact type come from? How can I get a. Net strongly typed object from an XML file? Why is context. Contacts its own query and what is context?

One feature of the EDM design tool is that the designer automatically executes code generation based on the model. The Model Designer. CS file is attached to the Model in solution manager, as shown in 3-1.

In solution manager, expand the. edmx file to view the generated code file and open the file to see what is there.

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

The generator reads the concept layer in the model, creates an objectcontext Based on entitycontainer from it, and creates an object class for each object in the model. 3-3.

The generated code file contains four classes. Figure 3-4 shows these classes in the class design view of. You can open a class in the class designer, right-click the class in solution manager, and select View class diagram.

In the default view, click "sampleentities" in the upper-right corner. This class uses the entitycontainer name of the model. Others are each entity, address, contact, and vofficeaddresses.

Objectcontext class, smapleentities

When you view the XML view of the model in Chapter 2nd, you can see the entitycontainer that contains entitysets and associationssets.

Sampleentities class represents entitycontainer, which inherits from the objectcontext type of EF. This is why the context variable is used in the example. Asmpleentities have three attributes: addresses, contacts, and vofficeaddresses. They are the entitysets defined in the model. The three addto methods created by code generation provide a new method for the context object instance, and then they are inserted into the database. These addto methods are backward compatible 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 sections.

Note: I used to use "context" as the variable name of the objectcontext instance when using EF to write code.

Take a closer look at the contacts attribute. You can see that it returns the objectset of the contact type:

Public objectset <contact> contacts

Note: For VB developers, if you are not familiar with the generic syntax, C # uses the tip registration to indicate the type, while VB uses the number form with the keyword. The previous code using VB looks as follows:

Public property contacts as objectset (of contact)

The basis of our query is objectset. Whether you want to query all the contact entities as in Example 3-1, or you want to request a subset as in Example 3-2. The write query for objectset is the same as the database query for writing database tables.

Entity class

The three entities defined in the model are the sources of the three entity classes. Each class is inherited from EF's entityobject and contains attributes defined based on the model. If necessary, it also includes the contact. Addresses and address. Contact navigation attributes. See Figure 3-5

But there is a new content in the Address class: contactreference, which is another way to access the contact attribute. You will learn details about the entityreference attribute in Chapter 19th. These classes have more members, but they are irrelevant to the queries made in this chapter. We will explain them in detail in subsequent chapters of this book.

In-depth understanding: do not be afraid to parse the generated code file in depth, but remember that the model can be modified and saved at any time when you make any changes.

Use LINQ to entities to query

The query syntax of LINQ to entities is easier to learn and use than that of entitysql. If you have used LINQ elsewhere, you may already be familiar with it. LINQ to entities can meet most of your query requirements.

When. Net 3.5 is added to the VB and C # languages. LINQ represents language integrated query, and LINQ to entities is an implementation of it.

Note: although f # does not support LINQ, the added package of F # Created by F # team provides LINQ query.

Note: originally written in LINQ, it is used to provide independent query languages for all CLR objects. Now it has many implementations. You just used an implementation to work with object objects. Vs and. net run time also include LINQ to SQL, which is a direct query implementation for sqlserver databases. Many third-party vendors have compiled the LINQ provider.

You can get a lot of creden by using LINQ queries, and you can easily find many books about linqr. It is helpful to understand the basic structure when you start learning it.

Write your first LINQ to entities Query

The query mentioned above uses a shortcut to provide query. But it is not like a real query. Now you will use the LINQ operator to compile the LINQ to entities query.

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

Example 3-2. a linq to entities query in VB and C #

VaRContacts =FromCInContext. Contact

WhereC. firstname ="Rebort"

SelectC;

Note: When writing a LINQ query, you will find the differences between the VB and C # syntaxes. Except for Case sensitivity, note that the select operator is not required for VB display, whereas C # is required.

Run the program again and you will see that only a small portion of contacts are listed, and their first names are all Robert.

The most obvious symbol integrated into a LINQ query is that smart sensing will help you when you knock on your query. For example, provide the optional firstname for variable C. This is because when you specify contacts in the query, the compiler can determine that the item in the set is the contact item. When you press C in the select and where clauses, intelligent sensing can list the attributes of the recommended contact.

Why does LINQ start from "from?

A linq query starts with the from clause, rather than the select clause in another query language that we are familiar. When LINQ is created, the query statement does start with the select clause. However, Microsoft developers quickly realized that identifying the types being used could enable intelligent sensing to provide more meaningful suggestions in the remaining queries.

According to Y. Alan griver, an early member of Microsoft's LINQ program, Microsoft developers joked that the syntax was "Yoda speak" when they modified the syntax for smart sensing ".

In the query, C is just an arbitrary variable name, allowing you to reference what you need after the query. It is called a control variable. Control variables provide another way for developers to intelligently perceive and compile the variables so that LINQ is more efficient for developers.

linqpad

linqpad is a powerful tool written by O 'Reilly, Joseph albahari (he has a file: LINQ pocket reference [http://oreilly.com/catalog/9780596519254/], C #4.0 in a nutshell [compile. 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 good way to test the query outside the application.

you can download linqpad in http://www.linqpad.net for free. There is a cheap (and worthwhile) update that allows smart sensing in this tool. On the linqpad website and download page, you will find many great tutorials to illustrate how to use linqpad and how to use it in EF.

many examples in this chapter only support queries. There are many excellent query tests in linqpad. Other examples involve tasks other than queries. You may want to execute these tasks in the console program according to the commands.

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.