Entity Framework 6 Recipes Chinese translation series (6), entityframework

Source: Internet
Author: User

Entity Framework 6 Recipes Chinese translation series (6), entityframework
2-5 Use Code First to model the self-reference relationship

Problem

A self-referenced table in your database, you want to use Code First to model it into a person containing self-associated entities.

Solution

Assume that you have a self-reference table for the database relationship diagram from 2 to 14.

Figure 2-14 a self-reference table

Follow these steps to model the self-referenced table and link:

1. Create a class EF6RecipesContext inherited to the DbContext context in the project.

2. Create a PictureCategoryPOCO (simple CLR object) object using code list 2-5.

Code List clearing 2-5 create a POCO entity PictureCategory

 1 public class PictureCategory { 2         [Key] 3         [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 4         public int CategoryId { get; private set; } 5         public string Name { get; set; } 6         public int? ParentCategoryId { get; private set; } 7         [ForeignKey("ParentCategoryId")] 8         public PictureCategory ParentCategory { get; set; } 9         public List<PictureCategory> Subcategories { get; set; }10         public PictureCategory() {11             Subcategories = new List<PictureCategory>();12         }13     }

3. Add a DbSet <PictureCategory> attribute to the created context object EF6RecipesContext.

4. Rewrite method OnModelCreating in EF6RecipesContext to configure two-way Association (ParentCategory and SubCategories), as shown in the code list from 2 to 6.

Proxy List 2-6 override method OnModelCreating

 

1 public class EF6RecipesContext: DbContext {2 public DbSet <PictureCategory> PictureCategories {get; set;} 3 public EF6RecipesContext () // the original text is incorrectly written as PictureContext () 4: base ("name = EF6CodeFirstRecipesContext") {5} 6 protected override void OnModelCreating (DbModelBuilder modelBuilder) {7 base. onModelCreating (modelBuilder); 8 modelBuilder. entity <PictureCategory> () 9. haswon (cat => cat. subCategories) 10. witexceptional (cat => cat. parentCategory); 11} 12}

    

Principle
The relational database has the following features: dimension (degree), multiplicity (multiplicity), and direction (derection ). A dimension is the number of entities (tables) in a link. One-dimensional and two-dimensional relationships are common. The Relationship Between 3d and n-dimensional (n-Place) only exists in theory.

Multiple refers to the number of object types at both ends of a link line segment. You may already have seen such a multiple representation: 0... 1 (zero or one), 1 (one), and * (many ).

Finally, the direction can be bidirectional or unidirectional.

The object data model supports the database relationships of popular databases. It is represented by an association type. A join type can be one-dimensional or two-dimensional, with multiple numbers 0... and *, and two-way directions.

In this example, the dimension is one-dimensional (only involving PictureCategory entities), the multiple dimensions are 0... 1 and *, and the direction is of course bidirectional.

In the example, a self-Reference Table generally refers to a parent-child relationship. Each parent has multiple children, and each child has only one father. Because the relationship between the father and the end is 0... 1 rather than 1. This means that the child may have no father. This can be used to represent the root node. A node without a father is the top of the hierarchy.

Code List 2-7 demonstrates how to recursively enumerate the image directories from the root node. Of course, the root node is a node without a father.

 1         static void RunExample() { 2             using (var context = new EF6RecipesContext()) { 3                 var louvre = new PictureCategory { Name = "Louvre" }; 4                 var child = new PictureCategory { Name = "Egyptian Antiquites" }; 5                 louvre.Subcategories.Add(child); 6                 child = new PictureCategory { Name = "Sculptures" }; 7                 louvre.Subcategories.Add(child); 8                 child = new PictureCategory { Name = "Paintings" }; 9                 louvre.Subcategories.Add(child);10                 var paris = new PictureCategory { Name = "Paris" };11                 paris.Subcategories.Add(louvre);12                 var vacation = new PictureCategory { Name = "Summer Vacation" };13                 vacation.Subcategories.Add(paris);14                 context.PictureCategories.Add(paris);15                 context.SaveChanges();16             }17             using (var context = new EF6RecipesContext()) {18                 var roots = context.PictureCategories.Where(c => c.ParentCategory == null);19                 roots.ForEach(root => Print(root, 0));20             }21         }22         static void Print(PictureCategory cat, int level) {23             StringBuilder sb = new StringBuilder();24             Console.WriteLine("{0}{1}", sb.Append(' ', level).ToString(), cat.Name);25             cat.Subcategories.ForEach(child => Print(child, level + 1));26         }

The output from the code list 2-7 shows that the root node is Summer Vacation. Its first (only one) child is Paris. Paris has children Louver. Finally, I accessed the directory set in the Louver photo directory.

Summer Vacation
Paris
Louvre
Egyptian Antiquities
Sculptures
Paintings

 

Obviously, the Code is a little more complex. We first create and initialize Multiple object types of instances, and add these image directories to the directory louver to add them to the object graph, then, add the louver directory to the paris directory, and then add the paris directory to the summer vacation directory. We built the entire inheritance system from the bottom up.

Once the SaveChange () method is called, all directories are inserted into the database. I can query the data in the table to see if all rows are correctly inserted.

For getting some code, we first get a root object, which is a directory without a parent. In this example, we create a summer vacation object, but it is not set to any physical child. This makes it the root node of the entire inheritance system.

Now, starting from the root node, we call another method we have written: Print (), Print () method to accept a pair of parameters. The first parameter is a PicturCategory instance object, the second parameter is an integer that represents a hierarchy or depth in the inheritance system. For the root directory, summer vacation, which is at the top of the inheritance system, we pass 0 to the print () method. The method call will be like this Prin (root, 0 ).

In the Print () method, we output the directory name and add leading spaces before the name according to the depth of the directory in the inheritance system. The method Append () of the StringBuilder class accepts two parameters: a character and an integer. It creates a StringBuilder instance and attaches a specified number of characters to the integer parameter. In our call, we use space and the level of the directory as the parameter, and it returns a space string of the number of directory depth. We call the Sostring () method of StringBuilder to convert the StringBuilder instance into a string instance.

Now, in the recursion section, we use children to iterate the child directory, call the Print () method for each child directory, and ensure that Levle increments. After the children traversal, we return the result. The final result is shown in the previous output.

In 6-5, we will show another method. Using table expressions in the stored procedure, the storage end can iterate through the relational graph, and then return a flat result set.

 

The topic of this article is over and I hope you will gain some benefits. Indicate the source for reprinting. Thank you.

 

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.