Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Task 6 – Modifying Database Data

In this task, you move beyond data retrieval and see how to manipulate the data. The four basic data operations are Create, Retrieve, Update, and Delete, collectively referred to as CRUD. You see how LINQ to SQL makes CRUD operations simple and intuitive. This task shows how to use the create and update operations.

 

 

5. Create a new method that modifies the database data as well as a call from Main:

static void ModifyData()

{

var db = new NorthwindDataContext();

 

Console.WriteLine("Number Created Before: {0}",

db.Customers.Where( c => c.CustomerID == "ADVCA" ).Count());

 

var newCustomer = new Customer

{

CompanyName = "AdventureWorks Cafe",

CustomerID = "ADVCA"

};

db.Customers.InsertOnSubmit(newCustomer);

db.SubmitChanges();

 

Console.WriteLine("Number Created After: {0}",

db.Customers.Where( c => c.CustomerID == "ADVCA" ).Count());

}

 

static void Main(string[] args)

{

ModifyData();

}

 

6. Press Ctrl+F5 to build and run the application. Notice that the two lines written to the screen are different after the database is updated. Now press any key to terminate the application.

 

Notice that after the Add method is called, the changes are then submitted to the database using the SubmitChanges method. Note that once the customer has been inserted, it cannot be inserted again due to the primary key uniqueness constraint. Therefore this program can only be run once.

 

7. Now update and modify data in the database. Change ModifyData to the following code that updates the contact name for the first customer retrieved.

 

static void ModifyData()

{

var db = new NorthwindDataContext();

 

 

Console.WriteLine("Number Updated Before: {0}",

db.Customers.Where( c => c.ContactName == "New Contact" ).Count());

 

var existingCustomer = db.Customers.First();

existingCustomer.ContactName = "New Contact";

db.SubmitChanges();

 

Console.WriteLine("Number Updated After: {0}",

db.Customers.Where( c => c.ContactName == "New Contact" ).Count());

 

}

 

8. Now press Ctrl+F5 to build and run the application. Notice again the number of contacts with the name “New Contact” changes. Press any key to terminate the application.

 


Date: 2015-02-03; view: 634


<== previous page | next page ==>
Task 5 – Querying using Expressions | Task 8 – Expanding Query Expressions
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)