For this example, I will be accessing a SQL table called person which looks like this
Id int
FirstName varchar(MAX)
LastName varchar(MAX)
Address varchar(MAX)
Age int
I have set the primary key on the id column.
In this example I will first perform a select,update, insert and delete in the old fashioned way using ado.net. Then I will perform the same actions using Entity Framework 5. I will be doing all this in a console application.
CRUD operations using ADO.net
Add this to your console application's app.config inside the configuration element. (Replace appropriate values
<connectionStrings> <add name = "ConnString" connectionString = "Data Source=myServerName; Initial Catalog=myDatabaseName;Integrated Security=False;User ID=myUserName;Password=myPassword" providerName = "System.Data.SqlClient" /> </connectionStrings>
Add to your project a reference to the System.Configuration.dll
This is how my console application solution looks like
Given below is the code
Program.cs
namespace EntityPlay { internal class Program { private static void Main(string[] args) { var dataAccess = new DataAccess(); //select Person person = dataAccess.GetPerson(1); //update (change his age to 60) person.Age = 60; dataAccess.UpdatePerson(person); //Insert John Doe var newPerson = new Person {FirstName = "John", LastName = "Doe", Address = "CT", Age = 28}; dataAccess.InsertPerson(newPerson); //Delete person with id 5 dataAccess.DeletePerson(5); } } }
Person.cs
namespace EntityPlay { public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public int Age { get; set; } } }
DataAccess.cs
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace EntityPlay { public class DataAccess { private readonly string _connectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString(); //SELECT public Person GetPerson(int id) { var person = new Person(); using (var conn = new SqlConnection(_connectionString)) { string commandText = @"SELECT * FROM Person WHERE Id=" + id; using (var cmd = new SqlCommand(commandText, conn)) { cmd.CommandType = CommandType.Text; conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { person.Id = id; person.FirstName = reader["FirstName"].ToString(); person.LastName = reader["LastName"].ToString(); person.Address = reader["Address"].ToString(); person.Age = Int32.Parse(reader["Age"].ToString()); } } } return person; } //UPDATE public void UpdatePerson(Person person) { using (var conn = new SqlConnection(_connectionString)) { string commandText = String.Format( @"UPDATE Person SET FirstName='{0}', LastName='{1}', Address='{2}', Age={3} WHERE Id={4}", person.FirstName, person.LastName, person.Address, person.Age, person.Id); using (var cmd = new SqlCommand(commandText, conn)) { cmd.CommandType = CommandType.Text; conn.Open(); cmd.ExecuteNonQuery(); } } } // INSERT public void InsertPerson(Person person) { using (var conn = new SqlConnection(_connectionString)) { string commandText = String.Format( @"INSERT INTO Person (FirstName, LastName, Address, Age) VALUES ('{0}','{1}','{2}',{3})", person.FirstName, person.LastName, person.Address, person.Age); using (var cmd = new SqlCommand(commandText, conn)) { cmd.CommandType = CommandType.Text; conn.Open(); cmd.ExecuteNonQuery(); } } } //DELETE public void DeletePerson(int Id) { using (var conn = new SqlConnection(_connectionString)) { string commandText = String.Format(@"DELETE FROM PERSON WHERE Id=" + Id); using (var cmd = new SqlCommand(commandText, conn)) { cmd.CommandType = CommandType.Text; conn.Open(); cmd.ExecuteNonQuery(); } } } } }
Now lets see how we can do the same operations doing entity framework
CRUD operations using Entity Framework
Follow these steps
1>Add entity framework 5 to your project using the nuget command
Install-Package EntityFramework -Version 5.0.0
2>Add an entity DataModel (this can be thought of as the code representation of your database)
Select generate from database in the next screen and click next and follow the instructions. Accept all the default settings. On the screen where we select tables, I just selected the Person table. I set my model namespace as PlayEntities.
This is how my code in the Program.cs looks like now
using System.Linq; namespace EntityPlay { internal class Program { private static void Main(string[] args) { Person person; using (var context = new PlayEntities()) { //select person = context.People.First(p => p.Id == 1); //Update person.Age = 60; context.SaveChanges(); } //Insert John Doe var newPerson = new Person {FirstName = "John", LastName = "Doe", Address = "CT", Age = 28}; using (var context = new PlayEntities()) { context.People.Add(newPerson); context.SaveChanges(); } //Delete using (var context = new PlayEntities()) { Person deletePerson = context.People.First(p => p.Id == newPerson.Id); context.People.Remove(deletePerson); context.SaveChanges(); } } } }
As you can see, once you set up the DataModel, you just need to work with the model. You don't need to worry about writing the lower level code that actually persists data it into the database.
No comments:
Post a Comment
Comments will appear once they have been approved by the moderator