Entity Framework 4.1/4.3 (DBContext 3 state tracking)

Source: Internet
Author: User

 

Entity Framework 4.1/4.3 (DBContext 3 state tracking)

 

  Let's talk about DBContext. This time the content will be consistent with the content mentioned in DBContext 2.

 

2. add, delete, and modify objects in DBContext (Adding, Changing, and Deleting Entities)

In DBContext 2, we talked about "add, delete, and modify", in which we already talked about "add, delete, and modify ". Some of the content is not mentioned. Let's complete it.

(1) Find The "Find or Add" Pattern)

Scenario: We often add a record. The add step is to first check whether the same record exists. If there is no lining, add the new record to the database. In the old version of EF, we will perform two operations: search first and Add. This virtually requires two interactions with the database.

DBContext provides us with a new solution, that is, Find or Add. Let's look at the Code:

    private static void FindOrAddPerson()    {      using (var context = new BreakAwayContext())      {        var ssn = 123456789;        var person = context.People.Find(ssn)?? context.People.Add(new Person        {          SocialSecurityNumber = ssn,          FirstName = "jerry",          LastName = "tom"        });        Console.WriteLine(person.FirstName);      }    }

The code looks very intuitive. If Find (ssn) finds this record in the cache or in the database, it will be output; otherwise, a new record will be added.

 

(2) Add link data (Adding a Relationship Between Objects)

To be honest, this is a bit difficult to understand. Let's take a look at the following code!

    private static void NewGrandCanyonResort()    {      using (var context = new BreakAwayContext())      {        var resort = new Resort        {          Name = "Pete's Luxury Resort"        };        context.Lodgings.Add(resort);        var canyon = (from d in context.Destinations                where d.Name == "Grand Canyon"                select d).Single();        canyon.Lodgings.Add(resort);        context.SaveChanges();      }    }

Destinations and Lodgings are one-to-many relationships. First, we create a resort object and add it to the Lodgings set. Then we find the parent set Destinations, add the resort object to the Lodgings set contained in Destinations, and then SaveChanges. This association is established and the corresponding data is saved to the database. In general, it means adding a record in the table first, and then linking the new record with the master table. Do you understand?

Here I want to emphasize that the relationship IDs of the two tables should be unified. For example, if the primary key in the primary table is classId, the associated slave table id should also be classId. If the primary key is not uniform, it is difficult for EF to automatically Map data, unless you manually re-Modify the ing relationship in the Map file.

 

(3) modify the relational data (Changing a Relationship Between Objects)

Private static void ChangeLodgingDestination () {using (var context = new BreakAwayContext () {var hotel = (from l in context. lodgings where l. name = "Grand Hotel" select l ). single (); var reef = (from d in context. destinations where d. name = "Great Barrier Reef" select d ). single (); hotel. destination = reef; context. saveChanges ();}}

Here is the SQL statement:
Exec sp_executesql n' update [dbo]. [Lodgings]
Set [destination_id] = @ 0
Where ([LodgingId] = @ 1)
', N' @ 0 int, @ 1 int', @ 0 = 4, @ 1 = 1

Here, Lodgings still plays the role of the slave table, and the Code temporarily shows the change of the master-slave table relationship. Of course, this is only a solution provided by DBContext. I personally prefer to directly modify the value of the Association ID.

 

(4) Removing a Relationship Between Objects)

      private static void RemovePrimaryContact()      {        using (var context = new BreakAwayContext())        {          var davesDump = (from l in context.Lodgings                    where l.Name == "Dave's Dump"                    select l).Single();          context.Entry(davesDump).Reference(l => l.PrimaryContact).Load();          davesDump.PrimaryContact = null;          context.SaveChanges();
        }      }

 

      private static void RemovePrimaryContact()      {        using (var context = new BreakAwayContext())        {          var davesDump = (from l in context.Lodgings                    where l.Name == "Dave's Dump"                    select l).Single();          davesDump.PrimaryContactId = null;          context.SaveChanges();        }      }

There is no such thing as deleting the link. One way is to leave the associated subset empty, and the other is to leave the associated id empty.

(5) briefly describe the tracking status. Here is just a brief introduction, and we will discuss it in detail later. (Working with Change Tracking)

Status List: • DbSet. Add
• DbSet. Find
• DbSet. Remove
• DbSet. Local
• DbContext. SaveChanges
• Running any LINQ query against a DbSet
• DbSet. Attach
• DbContext. GetValidationErrors
• DbContext. Entry
• DbChangeTracker. Entries

With these Tracking statuses, SaveChanges knows what it should do.

      

DetectChanges: The Controlling When DetectChanges Is Called control program will be triggered during change detection.

In most cases (or most of the time), the Entity Framework needs to know the Tracking Change (that is, the status Change of the trail) during SaveChanges ). Here is a definition that is not very easy to understand: the following is an application code in the Automatic DetectChanges, because at present I am not very accurate to the Automatic DetectChanges. So we only show the code and analyze it.

      private static void ManualDetectChanges()      {        using (var context = new BreakAwayContext())        {          context.Configuration.AutoDetectChangesEnabled = false;          var reef = (from d in context.Destinations                  where d.Name == "Great Barrier Reef"                  select d).Single();          reef.Description = "The world's largest reef.";          Console.WriteLine(            "Before DetectChanges: {0}",              context.Entry(reef).State);              context.ChangeTracker.DetectChanges();              Using Snapshot Change Tracking | 61          Console.WriteLine(            "After DetectChanges: {0}",              context.Entry(reef).State);        }      }

      private static void AddMultipleDestinations()      {        using (var context = new BreakAwayContext())        {          context.Configuration.AutoDetectChangesEnabled = false;          context.Destinations.Add(new Destination          {            Name = "Paris",            Country = "France"          });
          context.Destinations.Add(new Destination          {            Name = "Grindelwald",            Country = "Switzerland"          });          context.Destinations.Add(new Destination          {            Name = "Crete",            Country = "Greece"          });          context.SaveChanges();        }      }

I always think this is hard to understand.

(6) use the detectchanges Trigger Link (Using DetectChanges to Trigger Relationship Fix-up)

      private static void DetectRelationshipChanges()      {        using (var context = new BreakAwayContext())        {          var hawaii = (from d in context.Destinations                  where d.Name == "Hawaii"                  select d).Single();          var davesDump = (from l in context.Lodgings                  where l.Name == "Dave's Dump"                  select l).Single();          context.Entry(davesDump)              .Reference(l => l.Destination)              .Load();          hawaii.Lodgings.Add(davesDump);          Console.WriteLine(              "Before DetectChanges: {0}",                davesDump.Destination.Name);                context.ChangeTracker.DetectChanges();          Console.WriteLine(              "After DetectChanges: {0}",                davesDump.Destination.Name);        }      }

I hope the code can help us understand the truth.

(7) Enabling and Working with Change Tracking Proxies)

(8) Make sure that the New instance obtains the proxy (Ensuring the New Instances Get Proxies)

(9) create a Derived type Proxy instance (Creating Proxy Instances for Derived Types)

(10) Fetching Entities Without Change Tracking)

I don't know the benefits and advantages of 6, 7, 8, 9, and 10. If you know this, please let me know. I will first make mistakes I have used and understood. For some unknown fields, I hope you will not give any advice. Well, write it here. I am bailing.

 

Bailing Note: copyright of this ArticleBailing and the blog Park are both owned by each other. For more information, see the source.
Helping others is the same as self-help! Mbailing@163.com

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.