Identification of objects in-depth understanding of LINQ to SQL-uncle Michael disgusting clicks Blood

Source: Internet
Author: User
Tags shallow copy

Preface

A lot of friends have told me that I want to write about LINQ to SQL or VS plug-ins. Although there are many LINQ to SQL books on the market, they are all about how to use and lack depth. About VS plug-in aspects of the book is also very shallow, according to books made out of things, can only be student-level things, do not take the shot. They think I have the ability to write well.

From the point of view of technical ability, it is true that there is no problem, but it takes a long time to explaining a technology. I have paid a lot, if you can not get the reader's approval, then the topic written down is meaningless. The topic is not to teach you how to use LINQ to SQL, but to let you understand the principles of LINQ to SQL, not to be missed for friends who want to write Orm. After writing the series "in-depth understanding of Linq to SQL", the next series is "VS plug-in development", so if you want me to continue writing, please remember to recommend. Your recommendation is my motivation to write down.

Overview

As for the identity of the object, simply put, the object is the same as the primary key, and in the cache of the data context there is only one. The data context, after loading the data, creating the object, and then cloning a copy of the object for each entity class created (shallow copy) Remember this, we'll use it later to save the initial value of the object, and when the property value of the object is modified, the property value of the copy is not changed. Note that only the entity class object will create a copy of the object, and the anonymous class object will not generate a copy, or only an entity. Let's look at the following section of code:

Example One

var c1 = db. Categories.single (o = O.categoryid = = 1); var c2 = db. Categories.single (o = O.categoryid = = 1);

In this example, C1 and C2 are equal, let's take a look at the following example:

Example Two

var c1 = db. Categories.select (o = new {O.categoryid, o.categoryname}). Single (o = = O.categoryid = 1); var c2 = db. Categories.select (o = new {O.categoryid, o.categoryname}). Single (o = O.categoryid = = 1);

In this example, C1 and C2 are not equal.

Why do anonymous objects not support object identifiers? Because anonymous objects do not necessarily have a primary key. Linq to SQL, which identifies an entity object through the primary key of the entity, is not created until the data is loaded from the database, and the cache is retrieved based on the primary key for the object that already exists. What kind of problem does this cause? Execute the following code.

var c1 = db. Categories.single (o = O.categoryid = = 1);

Assuming that CategoryId is 1 CategoryName for "beverages", open the database and change the value to "New Name", such as:

Figure A

Then execute the following code:

var c2 = db. Categories.single (o = O.categoryid = = 1);

At this time C2 modified C2. What is the value of CategoryName? Still for "beverages"! Since the second time the data is loaded, because the primary key (CategoryID) is already in the category "1", the new object is no longer created in the second load to use the Category object created earlier. So how can you use C2 's CategoryName value as the newest value "New Name"? You can call the Refresh method of the data context.

Db. Refresh (refreshmode.overwritecurrentvalues, C2);
Tracking changes to Properties

Let's take a look at an updated example:

var c1 = db. Categories.single (o = O.categoryid = = 1); C1. CategoryName = "xxx";d B. SubmitChanges (); C1. CategoryName = "xxx";d B. SubmitChanges ();

By looking at the generated SQL, we can see that although the Submitchagens method executes two times, the SQL is actually executed only once because the second CategoryName is not modified, so how does LINQ to SQL know that a property is modified or not? We look at the definition of the category entity class, in order to save space, select only one part.

[Table (name= "Categories")]public partial class category:inotifypropertychanging, inotifypropertychanged{    [ Column (storage= "_categoryname", dbtype= "VarChar", Canbenull=false, Updatecheck=updatecheck.never)] public    String CategoryName    {        get        {            return this._categoryname;        }        Set        {            if ((this._categoryname! = value))            {this                . Oncategorynamechanging (value);                This. Sendpropertychanging ();                This._categoryname = value;                This. Sendpropertychanged ("CategoryName");                This. Oncategorynamechanged ();                    }}} protected virtual void sendpropertychanged (String PropertyName)    {        if (this. propertychanged = null))        {this            . PropertyChanged (This, new PropertyChangedEventArgs (PropertyName));}}}    

We can see that the entity class category implements the INotifyPropertyChanged interface, through which we can know whether a property has changed, but, in fact, the category entity class does not implement the above interface, is also no problem, As shown below:

[Table (Name = "Categories")]public partial class category{    [Column (Storage = "_categoryname", DbType = "VarChar (15)") , Canbenull = False, UpdateCheck = updatecheck.never)] public    string CategoryName    {        get {return This._catego Ryname; }        set {this._categoryname = value;}}    }

Why is this possible? Remember we were just talking about the object copy? When the category does not implement the INotifyPropertyChanged interface, Linq to SQL compares the category entity object with the original copy of the object to see if the category's property values have changed.

However, the following definition causes the value of CategoryName to be modified and not updated to the database. Because when the value of CategoryName changes, there is no notification to the interface INotifyPropertyChanged, and when the entity class inherits from INotifyPropertyChanged, the Linq to SQL is dependent on inotifypropertychanged to get the property that the value is changed.

[Table (Name = "Categories")]public partial class category:inotifypropertychanged{    [Column (Storage = "_ CategoryName ", DbType =" VarChar (UP) ", Canbenull = False, UpdateCheck = updatecheck.never)] public    string Categorynam E    {        get {return this._categoryname;}        set {this._categoryname = value;}}    }

From the above we can know, through the object identification, you can make the model definition is the most concise, in the LINQ to SQL design, you will often see, many places follow the principle of concise model, this principle, in the following content will be introduced to you. At the same time you will find that it is not possible to add, update, delete operations for entities that do not have a primary key defined, because these operations depend on the identity of the object, and the object identity requires the entity's primary key. Because the primary key is used to identify the object, the key cannot be changed.

Remark :

ALINQ provides the Insert, Update, and Delete three methods, which are three ways to simply turn Linq Lamdba expressions into SQL statements and then execute them. Therefore, it does not depend on the object identity. So it can:

1, no primary key can also be updated

2, you can update the value of the primary key

In short, SQL can manipulate it all. With regard to the use of these methods, ALINQ documents are described in the documentation.

It can not:

1, the method can not be replaced by the extension method.

For example: If you are using InsertOnSubmit (customer), you can replace the original method by overriding the InsertCustomer method. Of course you need to split a table into two, which is very useful. If you are using the Insert method, it is not valid.

2, ALINQ Inject injection framework cannot inject it.

Identification of objects in-depth understanding of LINQ to SQL-uncle Michael disgusting clicks Blood

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.