EntityFramework6.0 Reading Notes [2] ----- Entity Data Model basics [medium], Entity Data Model

Source: Internet
Author: User

EntityFramework6.0 Reading Notes [2] ----- Entity Data Model basics [medium], Entity Data Model
Multi-to-Multi-association model with no load

In the original article, it is Modeling a packet-to-packet Relationship with No Payload. Although the translation is a bit inaccurate, it can indicate its purpose, as shown in, the Relationship in the database is as follows,

Based on the Database Frist development mode, how many object will we get when we create a model by using the wizard?

From this we can see that this Many-to-Many Relationship object population requires the carrying and conversion of other entities, then Modeling a packet-to-Fetch Relationship with No Payload will mean this.

Let's see how it works:

       using (var context = new EF6RecipesContext__1())            {                // add an artist with two albums                var artist = new Artist { FirstName = "Alan", LastName = "Jackson" };                var album1 = new Album { AlbumName = "Drive" };                var album2 = new Album { AlbumName = "Live at Texas Stadium" };                artist.Albums.Add(album1);                artist.Albums.Add(album2);                context.Artists.Add(artist);                // add an album for two artists                var artist1 = new Artist { FirstName = "Tobby", LastName = "Keith" };                var artist2 = new Artist { FirstName = "Merle", LastName = "Haggard" };                var album = new Album { AlbumName = "Honkytonk University" };                artist1.Albums.Add(album);                artist2.Albums.Add(album);                context.Albums.Add(album);                context.SaveChanges();            }            using (var context = new EF6RecipesContext__1())            {                Console.WriteLine("Artists and their albums...");                var artists = context.Artists;                foreach (var artist in artists)                {                    Console.WriteLine("{0} {1}", artist.FirstName, artist.LastName);                    foreach (var album in artist.Albums)                    {                        Console.WriteLine("\t{0}", album.AlbumName);                    }                }                Console.WriteLine("\nAlbums and their artists...");                var albums = context.Albums;                foreach (var album in albums)                {                    Console.WriteLine("{0}", album.AlbumName);                    foreach (var artist in album.Artists)                    {                        Console.WriteLine("\t{0} {1}", artist.FirstName, artist.LastName);                    }                }            }
Create a multi-to-Multi-association model and add additional information

The above LinkTable only contains two foreign key information. EntityFramework does not generate an EntityType for this purpose. However, if some information is attached to the LinkTable, EntityFramework generates an EntityType for this purpose, two one-to-multiple associations are formed as follows:

The object relationship diagram generated by the Wizard is as follows:

Let's take a look at how it makes the work. [the code in the book is a bit problematic, and the correction is as follows]

using (var context = new EF6_2RecipesContext())            {                var order = new Order                {                    OrderId = 1,                    OrderDate = new DateTime(2010, 1, 18)                };                var item = new Item                {                    SKU = 1729,                    Description = "Backpack",                    Price = 29.97M                };                var oi = new OrderItem { Order = order, Item = item, Count = 1 };                context.OrderItems.Add(oi);                item = new Item                {                    SKU = 2929,                    Description = "Water Filter",                    Price = 13.97M                };                oi = new OrderItem { Order = order, Item = item, Count = 3 };                context.OrderItems.Add(oi);                item = new Item                {                    SKU = 1847,                    Description = "Camp Stove",                    Price = 43.99M                };                oi = new OrderItem { Order = order, Item = item, Count = 1 };                context.OrderItems.Add(oi);                context.SaveChanges();            }            using (var context = new EF6_2RecipesContext())            {                foreach (var order in context.Orders)                {                    Console.WriteLine("Order # {0}, ordered on {1}", order.OrderId,order.OrderDate);                    Console.WriteLine("SKU\tDescription\tQty\tPrice");                    Console.WriteLine("---\t-----------\t---\t-----");                    foreach (var oi in order.OrderItems)                    {                        Console.WriteLine("{0}\t{1}\t{2}\t{3}", oi.Item.SKU,                        oi.Item.Description, oi.Count,                        oi.Item.Price.ToString("C"));                    }                }            }

This is also the method recommended in the book to establish many-to-many relationships. Of course, in the initial stage of the project, additional information may not need to be added, and the first multi-to-many mode is formed, the book also provides the simplest and optimal solution, that is, to use an additional Int-type ID column in The LinkTable. In this way, it will reflect its flexibility in the future.

Build a self-Reference Model Using Model Frist

This is also the first case of using Code Frist in the book. We don't need to talk about self-reference here to see how to fulfill this requirement:

1. Create a PictureCategory POCO object

2. Create a class that inherits the DbContext

using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Data.Entity;namespace EntityFrameworkDemo{    public class PictureCategory    {        public PictureCategory()        {            Subcategories = new List<PictureCategory>();        }        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]        public int CategoryId { get; set; }        public string Name { get; set; }        public int? ParentCategoryId { get; private set; }        [ForeignKey("ParentCategoryId")]        public PictureCategory ParentCategory { get; set; }        public List<PictureCategory> Subcategories { get; set; }        }    public class PicturesContext : DbContext    {        public DbSet<PictureCategory> PictureCategories { get; set; }        public PicturesContext()            : base("name=PicturesContext")        {        }        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            base.OnModelCreating(modelBuilder);            modelBuilder.Entity<PictureCategory>()                .HasMany(cat => cat.Subcategories)                .WithOptional(cat => cat.ParentCategory);        }    }}

Next, let's analyze the relationship model involved in degree, multiplicity, and direction:
Degree [degree]: one dollar

Multiplicity [composite degree, which is common in UML, that is, repetition degree]: 0 .. 1 and *. Because a Parent has N children, each child can only have 1 Parent.

Direction [flow direction]: bidirectional

For more information about these terms, see here.

Database relationships are characterized by degree, multiplicity, and direction. Degreeis the number of entity types
that participate in the relationship. Unary and binary relationships are the most common. Tertiary and n-place
relationships are more theoretical than practical.
Multiplicityis the number of entity types on each end of the relationship. You have seen the multiplicities 0..1
(zero or 1), 1 (one), and * (many).
Finally, the directionis either one-way or bidirectional.
The Entity Data Model supports a particular kind of database relationship called an Association Type.
An Association Type relationship has either unary or binary degree, multiplicities 0..1, 1, or *, and a direction that
is bidirectional

How it works
  using (var context = new Recipe5Context())            {                var louvre = new PictureCategory { Name = "Louvre" };                var child = new PictureCategory { Name = "Egyptian Antiquites" };                louvre.Subcategories.Add(child);                child = new PictureCategory { Name = "Sculptures" };                louvre.Subcategories.Add(child);                child = new PictureCategory { Name = "Paintings" };                louvre.Subcategories.Add(child);                var paris = new PictureCategory { Name = "Paris" };                paris.Subcategories.Add(louvre);                var vacation = new PictureCategory { Name = "Summer Vacation" };                vacation.Subcategories.Add(paris);                context.PictureCategories.Add(vacation);                context.SaveChanges();            }

 


2 Reading Notes

Several articles:

Camel Xiangzi tells the tragic story of a rickshaw Xiangzi in the old Beijing city of China. Xiangzi came to the city, eager to work honestly to create life. With his belief in buying a car, he tried his best to make money, just like a small spinning top. Finally, Xiang Zi got the car he dreamed of. For Xiang Zi, he didn't know how many pairs he had worn. But the fate of people, the car was taken one after another, Xiangzi's dream fire went out again and again. However, Xiangzi still refused to give up and kept fighting again. Here, I can't help but be touched and pity. I am touched by the tenacity of Xiangzi's perseverance and hard work for the dream. I am tortured by the miserable fate of Xiangzi, however, you can feel pity in frustration and disappointment. This taught me to be strong in the face of difficulties and stand up on your own if you fail. Later, from the combination with Tiger girl to the final death of Tiger girl, Xiangzi's mind was deeply affected. In the end, the car was sold, and the Tiger girl died. Everything turned to nothing, and it was just like the beginning. Everything is like wiping pen marks with an eraser. It will evaporate everything, leaving only a few deep marks. In Xiangzi's heart, deep marks are always branded. Xiangzi was so hostile to the world that he began to avenge everyone around him. In the past, Xiangzi, who spoke about righteousness, began to cheat his friends and use them to steal everything from them. He became treacherous and even shameless. He has changed a person, and he has done everything as long as he can get the money. I can't help but feel sad, disappointed, and angry. We are disappointed that Xiangzi did not stick to it and was eventually swallowed up by the darkness. The angry thing is that the honest and honest Xiangzi has done everything to hurt the truth,
He had no regrets. Xiang Zi's tragedy is the product of his social life environment. In a dark society, the power of mankind is too small. Xiang Zi tried to defeat his fate multiple times, but in the end, his mind and body were bruised again. Xiang Zi struggled again and again in pain, and gradually became distorted and swallowed up by the darkness. In the past, I was ambitious and full of bones. Now I only have to read money. Under the temptation of darkness and money in society,
Xiangzi has no backbone. "Money will introduce people into a bad society, put aside noble ideals, and be willing to go to hell ." Indeed, Xiangzi strives for money for "life". In "life" and "ideal", he chooses "life" because "life" is the only thing that the poor can choose. At that time, the life of the poor may be like the two leaders of the jujube kernel-don't starve to death when you are young; fortunately, it is very difficult to starve to death when you are old. At this time, we realized that the fate of people is not completely controlled by ourselves. Xiangzi, the hero of the story, struggled with his life with a tough character and Persistent attitude. But in the end, his fate still ruined Xiangzi. In a dark society, human nature becomes distorted, and people are filled with hatred ......

Everyone has read the Water Margin. Does anyone find that this is a hero novel, while the Romance of the Three Kingdoms is a historical romance.
Moreover, Shi Nai has made a lot of adaptations to the hacker, which was originally written at the center of "Liang shanpo Notepad". However, Shi Nai pays more attention to the fate of heroes, several of the important figures have personal biographies. The author concatenates them in the form of "column transfer. However, Shi Nai did not completely forget the historical events. Before the "Heroes of Liangshan Park" event, there was a historical event "three dozen Zhu jiazhuang. After the "Heroes of Liangshan Park" incident, I wrote another incident, such as Zhao 'an, and there was no independent personal biography.
In my opinion, it is wrong for Song Jiang to be promoted as the boss because of the following reasons:
1. He won't do the martial arts himself. You know which hero won't do the martial arts at the time. But what about Song Jiang? It's just a scholar with no help.
2. He was brave and helpless. During daily battles, most of his tactics were intended by Military Division Wu, and he did not do much work.
3. he did a very wrong thing, that is, Zhao 'an. after being recruited, I was very sad to be separated from my brother. after being enlightened by the Court, several people were taken together to die.
The Water Margin is different from the Romance of the Three Kingdoms, which can be seen from the historical data.
The Romance of the Three Kingdoms was cited by Chen Shou's Three Kingdoms and Pei songzhi's Three Kingdoms. The Song Jiang uprising described in the Water Margin has been recorded in the books of Song Shi, but they are very simple. It can be noted that the author has written many short stories about small... the remaining full text>

20 Reading Notes and 20 reading diaries each

Thoughts on reading fate

A few days ago, I bought a book In Shucheng, called "dripping water, hiding the Sea". There are 300 classic philosophical stories in it. Now I will taste a little story called destiny.
Destiny refers to the fate of a single child. One is Divination by a monk as "champion" and the other is "beggar ". Two decades later, the original "champion" became a beggar, while the "beggar" became a "champion ".
God said: "I give everyone 1/3 of his fate, and the rest is how to grasp it ."
After reading this passage, I was very touched. There are many simple words to grasp and grasp fate, but how many people really grasp their own destiny? You don't have to blame your talent, let alone your own destiny, because fate is in your own hands and you can change it at any time! If you want
Reading "never mind weapons"
A person who has said goodbye to weapons is either a prisoner of the enemy or a prisoner of love. I am not very good at self-protection. I am really a person who gives up self-protection. just like the database of life, you can open all programs and read all files at any time without entering the password. what I am talking about is a prisoner in this sense. when I put myself in the sun, I realized that there was no disguise, and the days of concealment were disturbing. when I realized that the resistance was helpless, how much time was irretrievable, and how much memory gradually fades out from my heart. after all, a prisoner is a person who cannot resist harm, that is, to have enough courage to give up hope and must bear all the pressure to survive. originally, in a personal space, you can immerse yourself in your own fantasies, and you can create virtual flowers from the dust. a person who gives up self-protection cannot cheat himself, only by constantly purifying the inner world.

After reading the paper of hampir
Shakespeare's "Hamlet" is a classic masterpiece. on the surface, this book is not much different from historical legends. It tells the story of Prince Denmark's revenge for his father, which is full of bloody violence and death. as
Horazu, a Chinese character in the drama, said: you can hear rape and kill, unusual repairs, decisions in the dark, accidental slaughter, tactics of killing by hand, and self-harm ending. the twists and turns of the plot, closely around revenge
Expand. he hurried back to China from wandunburg, Germany to attend his father's funeral. What makes him unacceptable was that he did not catch up with his father's funeral, he witnessed the wedding of his mother and uncle kraudis, which had made hamwright suspect. In addition, at night, he met his father's dead soul on the terrace of the palace Castle and mourned, this violent behavior was done by Uncle James and asked him to avenge his father. so far, he began a difficult revenge process, and began a battle with kradis. in the end, the sword of revenge was issued to kradiss.

Count of Christchurch
Love is complete, hate is thorough. the reward is complete, and the revenge is complete. this is what I feel most after reading "Revenge of Christchurch. there is a saying in China that revenge of a gentleman is not too late for ten years. Revenge also needs to be refined and powerful, and it is not just a matter of time. the Count of Christchurch explained the saying most specifically with his own actions. after 14 years of his career in the dungeon, his life is to find his loved ones, beneents, and enemies. after confirming the person we are looking for, he did not go through the fire as we have seen in martial arts novels. he chose his own method. for the ship owner who once had favor with him, he did his best and silently supported him. In various ways, he never let them know that he was actually here for good. if his reward is touching, his revenge is so full that we are a little surprised when we have a few bits.
Interpretation of dreams
Freuch (1856 -- l939) is a famous Austrian psychologist and founder of the School of spiritual analysis. his work spans half a century and has a wide and profound influence on literature, philosophy, theology, ethics, aesthetics, political science, sociology, and mass psychology, if we use the scope of the impact as a measure of greatness, then freusi is undoubtedly the greatest psychologist. in the history of human thoughts, freuch initiated another revolution of the neighborhood. He pointed out that the human consciousness cannot be controlled by consciousness, and the human subconscious contains a huge psychological content, in his most rational voice, he told us about the irrational nature of mankind. interpretation of dreams is Frolo ...... remaining full text>

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.