ORM programming technique in C#
In most of the applications, to achieve loose coupling, we maintain an ORM layer between a software application and the database, which maps database tables to C# entities.
ORM Layer
ORM layer is responsible to map database tables to c# entities and visa versa.
We have many ORM libraries available in C#, out of which the below are some main libraries
- Entity framework
- Dapper
- NHibernate
Dapper
Dapper is an ORM library, which extends methods of IDbConnection interface. These extension methods have efficient code to perform insert, update delete and select methods. These extension methods are,
- Execute
- Query
- QueryFirstOrDefault
- QuerySingle
- QuerySingleOrDefault
- QueryMultiple
Let’s start with the implementation of CRUD operation using dapper.
Step 1
Create table Student (Id Int Identity, Name Varchar(100), Marks Numeric)
Step 2
Step 3
- <Grid Margin="0,0,-31,-189">
- <DataGrid x:Name="studentDataGrid" x:Uid="employeeDataGrid" SelectionMode="Single" Height="auto" MaxHeight="300" HorizontalAlignment="Left" Margin="62,140,25,214" ItemsSource="{Binding}" AutoGenerateColumns="False" Grid.ColumnSpan="2">
- <DataGrid.Columns>
- <DataGridTextColumn Binding="{Binding Id}" Header="ID" x:Name="id" IsReadOnly="True" Width="Auto"></DataGridTextColumn>
- <DataGridTextColumn Binding="{Binding Name}" Header="Name" x:Name="name" Width="Auto"></DataGridTextColumn>
- <DataGridTextColumn Binding="{Binding Marks}" Header="Marks" x:Name="city" Width="Auto"></DataGridTextColumn>
- <DataGridTemplateColumn Header="Edit">
- <DataGridTemplateColumn.CellTemplate >
- <DataTemplate>
- <Button Content="Edit" Click="Edit_Click" CommandParameter="{Binding id}"></Button>
- </DataTemplate>
- </DataGridTemplateColumn.CellTemplate>
- </DataGridTemplateColumn>
- <DataGridTemplateColumn Header="Delete">
- <DataGridTemplateColumn.CellTemplate >
- <DataTemplate>
- <Button Content="Delete" Click="Delete_Click" ></Button>
- </DataTemplate>
- </DataGridTemplateColumn.CellTemplate>
- </DataGridTemplateColumn>
- </DataGrid.Columns>
- </DataGrid>
- <TextBox Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="143,34,0,0" Name="txtName"/>
- <Label Grid.ColumnSpan="2" Content="Name:" HorizontalAlignment="Left" Margin="48,34,0,0" VerticalAlignment="Top" Target="{Binding ElementName=txtName}"/>
- <Label Grid.ColumnSpan="2" Content="Marks:" HorizontalAlignment="Left" Margin="52,68,0,0" VerticalAlignment="Top" Target="{Binding ElementName=txtMarks}"/>
- <TextBox Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="143,68,0,0" x:Name="txtMarks"/>
- <Button x:Name="btnsubmit" Grid.ColumnSpan="2" Content="Submit" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="109,100,0,0" Click="InsertOrUpdateStudent"/>
- </Grid>
Here we are creating UI only. This can be done in many ways according to the requirement. This UI is just to show implementation.
Step 4
- public class Student
- {
- public int Id{get;set;}
- public string Name{get;set;}
- public int Marks {get;set;}
- }
Packages
Step 6
- private string sqlConnectionString = @"Data Source = YourDatabaseServerAddress;initial catalog=YourDatabaseName;user id=YourDatabaseLoginId;password=YourDatabaseLoginPassword";
- //This method gets all record from student table
- private List<Student> GetAllStudent()
- {
- List<Student> students = new List<Student>();
- using (var connection = new SqlConnection(sqlConnectionString))
- {
- connection.Open();
- students = connection.Query<Student>("Select Id, Name, Marks from Student").ToList();
- connection.Close();
- }
- return students;
- }
- //This method inserts a student record in database
- private int InsertStudent(Student student)
- {
- using (var connection = new SqlConnection(sqlConnectionString))
- {
- connection.Open();
- var affectedRows = connection.Execute("Insert into Student (Name, Marks) values (@Name, @Marks)", new { Name = student.Name, Marks = student.Marks });
- connection.Close();
- return affectedRows;
- }
- }
- //This method update student record in database
- private int UpdateStudent(Student student)
- {
- using (var connection = new SqlConnection(sqlConnectionString))
- {
- connection.Open();
- var affectedRows = connection.Execute("Update Student set Name = @Name, Marks = @Marks Where Id = @Id", new { Id = studentId, Name = txtName.Text, Marks = txtMarks.Text });
- connection.Close();
- return affectedRows;
- }
- }
- //This method deletes a student record from database
- private int DeleteStudent(Student student)
- {
- using (SqlConnection connection = new SqlConnection(sqlConnectionString))
- {
- connection.Open();
- var affectedRows = connection.Execute("Delete from Student Where Id = @Id", new { Id = studentId });
- connection.Close();
- return affectedRows;
- }
- }
Step 7
Points to be noted:
While using SQL database dapper uses ‘@’ symbol in query syntax, whereas it uses the ‘:’ symbol when using Oracle database.
Conclusion
- Dapper is a faster object-relational mapping tool. It performs very well on bulk data.
- Easy to write code.
- Excellent entities mapping.
Comments
Post a Comment