{%Pragmatic Coding%} Tips and tricks for software developers.

25May/121

Entity Framework: Insert, Update, Delete records

Every .NET developer sometime will start using ADO.NET Entity Framework.
And first question will be such as how to insert, update and delete records.
Performing basic Inser, Update and Delete operations via the Entity Framework is very straight forward.

Before you make any of thase operations you need to declare entyty


Inserting

To Insert the record we can write the following code:

As you can se it's really simple 2 lines of code sample. If you you have entity objects with small amount of data, like, FirstName and LastName you can use next  code to perform inserting:

This will create new istance of Student object with first and last name and perform inserting. For a good coding please use try{}catch{} and check values for null.

Updating

To Update the record we can write the following code :

But what if the object we are updating contains a lot of attributes.  Surely updating each attribute seperately before calling a Save is a little overkill.

Luckily we are providied with a solution which allows us to attach to a record within the context, perform a straight replace on the record with the new modified record and save back the changes, and all in just 3 lines of code:

It makes updating short coded and developer life easier.

Deleting

And finaly, perfoming Insert and Update operations we need to perfome Delete operetion also.

Sample deleting code operetion is below:

FirstOrDefault - gives us null object or first found record.

Also we can perform deleting by passing just a value of Student Id:

As you can see, nothing easier could be.
Happy coding!

Share on social network

Share to Facebook
Share to Google Plus
Share to LiveJournal
Share to MyWorld
Share to Odnoklassniki
Share to Yandex
Comments (1) Trackbacks (0)

Leave a comment

No trackbacks yet.