Here I am showing how to implement Insert , Update and Delete operation using
Linq to Entity Framework.
1. Insert Operation
Below is the code which is used to perform insert operation in the table.
In the code there is one table named AMSChannelsAgreementMap in
which I am inserting the data.
This table contains two columns ChannelId and AgreementId. Here I assigned
values to this columns. After that I called AddObject() which add this data to
table. db.SaveChanges() is used to commit the transaction.
//AMSEntities is name of Connection string
using (AMSEntities db = new AMSEntities())
{
/*AMSChannelsAgreementMap is the table name */
/*Create object of type AMSChannelsAgreementMap */
AMSChannelsAgreementMap chAgrMap = new AMSChannelsAgreementMap();
/*Assign values to each property of the object chAgrMap*/
chAgrMap.ChannelId = singlechannel;
chAgrMap.AgreementId = AgreementNumber;
db.AMSChannelsAgreementMaps.AddObject(chAgrMap);
try
{
db.SaveChanges();
}
catch
{
throw;
}
}
2. Update Operation
Below is the code which shows update operation on the table named
AMSClass_master.
Here I first selected the record which I am going to update. Then I
assigned new values to each column selected column. Then I called
SaveChanges() method to update the records.
public void UpdateClassMaster(int classCode, string includedTerritory, string excludedTerritory)
{
AMSEntities context= new AMSEntities()
/*Get Row for updation into var query depending on condition*/
var query =
from row in context.AMSClass_master
where row.class_code==classCode
select row;
// Execute the query, and change the column values
// you want to change.
foreach (AMSClass_master column in query)
{
column.include_territory = includedTerritory;
column.exclude_territory=excludedTerritory;
// Insert any additional changes to column values.
}
// Submit the changes to the database.
try
{
context.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
// Provide for exceptions.
}
}
3. Delete Operation
Here I deleted the records from the table named AMSClass_continent_master.
DeleteObject() is the method which is used to delete the records from the table.
/*Delete already exist record for perticular class code*/
public void DeleteExistingRecords(int oldclassCode)
{
/*Delete records from table AMSClass_continent_master*/
var deleteContinents =
from details in context.AMSClass_continent_master
where details.class_code==oldclassCode
select details;
foreach (var detail in deleteContinents)
{
context.AMSClass_continent_master.DeleteObject(detail);
}
try
{
context.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
No comments:
Post a Comment