Entityframework, one of the Entity Framework skill Series

Source: Internet
Author: User

Entityframework, one of the Entity Framework skill Series

The original series is from English.

Tip 1: How to sort the relationship (Relationships) in Entity Framework)

Problem:

In the Entity Framework forum, you will often see questions about sorting associated projects.

For example, imagine you want to query the customer and return the accounts that owe more than 30 yuan, while searching the orders of these accounts.

And you need to sort those orders by order date, so that you can first see the most recent order, so that you can easily find suspicious behavior.

Answer:

Most people may know that EF can use Include () to load a link instantly. Example:

1 var lateCustomers = from c in ctx.Customers.Include("Orders") 2                     where c.IsMoreThan30DaysInArrears 3                     select c;

Unfortunately, the orders of each customer returned by this statement are unordered.

So how do you sort these orders? Strictly speaking, there is no way.

But you can also do some such work, such as the include operation in the select clause.

1 var lateCustomers = from c in ctx.Customers 2                 where c.IsMoreThan30DaysInArrears 3                 select new {  4                     Customer = c,  5                     Orders = c.Orders.OrderByDescending( 6                                  o => o.OrderDate 7                              )  8                 }; 

This statement uses the standard LINQ syntax to request an anonymous iteration consisting of the customer and all the orders sorted by it.

Entity Framework can support this method, so the problem is solved...

Additional knowledge:

The above practices are somewhat...

Instead of using entities to retrieve data, I used other things-An anonymous type.

This method is not ideal.

You really want to access the customer's order through the customer. Orders attribute. It is interesting that even if something named Fix-up has achieved this goal.

The object service of Entity Framework automatically binds related items together. This process is called Fix-up.

Generally, the Fix-up process occurs when two associated entities enter the context.

So because I have loaded both Customer and Orders (via projection), the Fix-up will also ensure that the customer. Orders attribute contains those Orders. This is the real reason why Include ("Orders") is not used in my query.

This avoids the problem and leads to a new problem: Can Customer. Orders be sorted?

Unfortunately, there is no official solution.

This is not a feature we want to support. We don't have to spend time-we need to test it to make sure it works in every scenario. You know that is an important QA issue.

Although there are opponents, this can work in any way...

Why?

My guess is to execute sorting in the query. Writing code based on DataReader to instantiate the object and finally Fix-up has side effects.

Now, theoretically you can use this feature in the project... However, note that this is a big turning point. Please understand that this is not recommended.

Depending on a special implementation with potential negative effects, there is always a risk.

 

Tip 2. Entity Framework books

Problem:

Where can I find a book to learn more about Entity Framework?

Answer:

One advantage of developing products in the Microsoft product team is that you can access the author who wants you to review their books.

So far, I have received three copies of their Entity Framework books from different authors.

As follows:

 

ADO. NET Entity Framework-Unai Zorrilla Castro/Octavio Hernandez/Eduardo Quintas

This book is written in Spanish and is essentially a single language, so it is difficult for individuals to comment on its quality. However, it is enough for me to recommend this book by my colleagues in Argentina. Even so, I still like to put it on my bookshelf, which makes me very advanced... So thank you, Unai.

 

Programming Entity Framework-Julie Lerman

I have met Julie several times and I know that she has devoted her painstaking efforts to it. So it is not surprising that this nearly 800-page book is so thorough. Julie's book contains a lot of useful information and some practical examples.

Julie, thank you for your book.

 

Professional ADO. NET 3.5 with LINQ and the Entity Framework-Roger Jennings

I have never met Roger, but he knows from his blog that he makes us feel reliable. His book is a little different from Julie's book because it tells about other things around Entitiy Framework, such as LINQ to XML and LINQ to DataSet. I just received this book yesterday (Thank you Roger), but I believe it is very market-oriented.

 

As you can see here, these are good choices...

Wish your Entity Framework a smooth journey

 

Tip 3. Start a tour of T4

If you have read the Entity Framework Design Blog, you should have heard about T4. This is a technology released together with Visual Studio 2008 (2005 has an independent version for download ).

In. NET4.0, Entity Framework uses T4 to enhance code generation and model initialization.

In fact, T4 is also used in other major Microsoft products, including ASP. net mvc and Dynamic Data.

So if you want to start using T4 and get familiar with this technology, what should you do?

In fact, this technology is relatively simple. You can easily accomplish something quite useful:

 

  • Add a text file to the project and change the extension to ". tt ".
  • Write some template code in a text file.
    <# @ Import namespace = "System. Collections. Generic" #>
    <#
    Dictionary <string, Type> properties = new Dictionary <string, Type> ();
    Properties. Add ("Age", typeof (int ));
    Properties. Add ("Firstname", typeof (string ));
    Properties. Add ("Surname", typeof (string ));
    #>
    Using System;

    Public class <# = "MyClass" #> {
    <# Foreach (string name in properties. Keys) {#>
    Public <# = properties [name]. Name #> <# = name #> {
    Get; set;
    }
    <#}#>
    }

These template codes generate a class and use each Key in the dictionary named "properties" as its attribute.

  • Save the ". tt" file. When you complete this step, it is incredible that a template-dependent ". cs" file will automatically appear, as shown below:
     1 using System;  2  3 public class MyClass{  4       public Int32 Age{  5             get; set;  6       }  7       public String Firstname{  8             get; set;  9       } 10       public String Surname{ 11             get; set; 12       } 13 }

     

As you can see, T4 is very simple and easy to use for users familiar with ASP. NET...

Give it a try.

 

Tip 4: define language rules in conceptual Mode

The Entity Framework of the first version was released with. NET 3.5 SP1 not long ago.

One of the biggest vulnerabilities in the Entity Framework documentation is the lack of a formal description of the CSDL (concept mode Description Language.

What people want to know about CSDL is the specific format used by Entity Framework to describe the Entity Data Model (EDM.

These rules can be embeddedSystem. Data. Entity. dllThe XSD in the Assembly resources is pushed out, but a large number of rules are restricted by the Entity Framework itself.

If you are interested in the details of these rules, see formal CSDL specification here.

This document focuses on the CSDL1.1 version used by Astoria, but most of the CSDL1.0 and 1.1 versions are the same. These differences are clearly listed here.

Disclaimer: I helped edit some parts of this document. If you have any problems, please let me know.

 

Tip 5: How to restrict the types returned by EF queries

Consider that you have a model like this:

 

How to query only Cars?

 

This is when OfType <SubType> () was launched. You can write the following code:

1 var onlyCars = from car in ctx.Vehicles.OfType<Car>() 2                select car;

And this can work well. This limits the results to Cars, with Cars and Sports included.

How to query only Cars without its subtype?

Consider that your budget is enough to select a simple household car. This means that you do not want an SUV or a sports car (SportsCars ).

You need to specify the limit in the query to avoid returning all child types:

1 var onlyCars = from car in ctx.Vehicles.OfType<Car>() 2                where !(car is SportsCar) && !(car is SUV) 3                select car;

Now, your code only returns Cars-type objects.

Upload

The only pity about this solution is that you have to display and exclude all child types that you might not want. In some cases, there may be many sub-classes with multi-level inheritance or a large number of derived classes at a level.

It would be better if the following statement is supported (unfortunately this is not supported ):

1 var onlyCars = from car in ctx.Vehicles.OfType<Car>() 2                where car.GetType() == typeof(Car) 3                select car;

The problem is, How important do you think it is to support this type of query?

 

BTW: C # Why does the data structure and algorithm series have been translated? This book has already been available in Chinese versions (see for details) and I will not repeat it ..

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

Related Article

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.