EntityFramework 5.0 Codefirst Tutorial 02-Delete and modify/Schema change exception handling

Source: Internet
Author: User

-----------------------------------------------------Directory-----------------------------------------------------

EntityFramework 5.0 Codefirst Tutorial 01-Build the environment and get started quickly (2015-07-13 10:48)

EntityFramework 5.0 Codefirst Tutorial 02-Delete and modify/Schema change exception handling (2015-07-14 17:50)

-----------------------------------------------------Directory-----------------------------------------------------

in the last section, we set up a simple environment, and through code first, we build the database, create the data table, add records to the data table, find the data in the data table, we learn to get one of the records, modify the record, and then delete a record.

The first is to get a record, such as getting the first record
// get a piece of data using (varnew  Context ()) {    var savedpeople = context. People;     if (Savedpeople.any ()) // true if the source sequence contains any elements, or false if there is a record    in the table {       var person = Savedpeople.first ();   Gets the first       string name = person. FirstName; // Get Data    }}

If you want to get a piece
var 1  var p2 = context. People.find (PERSONID); // gets the record to delete through the primary key ID
Now that we can get a piece of data, we can modify the data below, for example, we want to change the FirstName
  //Modify a record            using(varContext =NewContext ()) {                varSavedpeople =context.                People; if(Savedpeople.any ())//true if the source sequence contains any elements, or false if there is a record in the table                {                    varperson = Savedpeople.first ();//get the first articlePerson. FirstName ="www.bamn.cn";//Modify NamePerson. LastName ="Benson"; Context.                SaveChanges (); }            }


Then delete a record to delete a record, in fact, very simple, we can get a record based on the ID, then to delete this record, only need to get this communication and call the context of the Remove method can delete this record, but there is a note, is deleted to remember SaveChanges oh.
    // Delete a record using (varnew  Context ()) {     var2;     var person = context. People.find (PERSONID); // gets the record to delete through the primary key ID    if NULL )    {       context. People.remove (person);       Context. SaveChanges ();    

------------------------------------------------------------------------------Well, the last shot inside we basically implemented the creation of the database to create new query modification Delete, But we've always been working on a single table, that is, the person table, our data structure has not changed, but this is definitely illogical, we certainly need other tables, or to modify the existing tables, this time we operate to find error, first we add a company's class
     Public class company    {        publicintgetset;}          Public string Get Set ; }    }

Very simply, there is only one primary key and one name and then add a dataset public dbset<company> Companies {get; set;} in the contextual context. After this modification, when we run our program, we will report the following errorunhandled exception of type "System.InvalidOperationException" occurs in EntityFramework.dllAdditional information: The model backing the ' context ' context has changed since, the database was created. Consider using Code first migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).  This time, we need to use another method to reconstruct our data structure to define a initializer class dropcreatedatabaseifmodelchanges<context> This is a generic class and then overrides the seed factor method
protected Override void Seed (Context context)        {            context. Companies.add (new  company            {                "Mycompany" )            });        }

In this method, we add a record to the table, the seed side play after the execution of the original operation will not be triggered, of course, we will have a better way to deal with the problem of structural change, our future course will learn the problem ... After execution, the code does not report an exception, and a new table is added companies all the code in this episode #region the second lesson
 //get a piece of data//using (var context = new context ())//{            //var savedpeople = context.            People; //if (Savedpeople.any ())//true if the source sequence contains any elements, or false if there is a record in the table//    {            //var person = Savedpeople.first ();//get the first article//string name = person. FirstName;//Get Data//var personId = 1; //var P2 = context. People.find (personId);//gets the record to delete through the primary key ID//    }            //}             //Modify a record//using (var context = new context ())//{            //var savedpeople = context.            People; //if (Savedpeople.any ())//true if the source sequence contains any elements, or false if there is a record in the table//    {            //var person = Savedpeople.first ();//get the first article//Person . FirstName = "www.bamn.cn";//Modify Name//Person .            LastName = "Benson"; //context.            SaveChanges (); //    }            //}             //Delete a record//using (var context = new context ())//{            //var personId = 2; //var person = context. People.find (personId);//gets the record to delete through the primary key ID//if (person! = null)//    {            //context.            People.remove (person); //context.            SaveChanges (); //    }            //}             #endregionDatabase.setinitializer (NewInitializer ());//after you cancel the database schema modification             using(varContext =NewContext ()) {               BOOLres =context.               Database.createifnotexists (); //adding data to the database               varperson =NewPerson {FirstName="John", LastName="Doe"               }; Context.               People.add (person); Context.                SaveChanges (); //Get Data               varSavedpeople =context.               People; foreach(varPinchsavedpeople) {Console.WriteLine ("Last name:{0},first name:{1},id {2}", P.lastname, P.firstname, P.personid); }} console.readkey ();
-------------------------------------------------All right, let's start with this episode. Here we come to the next episode to learn a more complex data structure .... This set of code: Http://pan.baidu.com/s/1gd0FxsR More EF information, you can login to my homepage ... Thank you for reading ....

EntityFramework 5.0 Codefirst Tutorial 02-Delete and modify/Schema change exception handling

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.