C# First dapper App Flashcards
(21 cards)
Get connectionString from app.config
ConfigurationManager.ConnectionStrings[name].ConnectionString
(In the static helper class using a static method)
Add connection string in config.app
In configuration
< add name=“sampledb” connectionstring=“server=.;database=sample;trusted_connection=true;” ProviderName= “system.data.sqlClient”>
Step to have a simple c# app connected to sql with windows form
Define class Add helper to get connection string Define connectionstring in config.app Define ui Add dataaccess class Use an instance of dataaccess to get the result (usually db) Add dapper reference in DataAccess class
How to not make crash a function that you havent implement yet
Add in the code: Throw new NotaimplementedException();
Connect a list to a listbox
Mylistbox.DataSource=peopleList
MyListBox.DisplayMember=“myProperty”
With peopleList is a list.
No need to have a bindingsource anymore.
The property is in double quote, make sure to write it properly.
Property that return a string that is a list of existing property using $ sign
Return $”{property1} {property2} ({property3})”
Add dapper reference
Go to reference, right click, select manage nuget packages,browse dapper, can add using dapper at the top of your dataAccess class
Using statement with dapper
Using (IDBConnection connection =system.data.sqlclient.sqlconnection(myConnectionString))
{
}
If you have an helper, instead of myConnectionString then
Helper.connval(myname);
Dapper query with direct sql and result is return by a function
Return Connection.query($”select * from people where name=‘{myName}’ “).ToList();
With connection of type IDBConnection
Dapper query with store procedure
Var output= connection.Query(“dbo.mystoreProcedure @myProcVariable”,new { myProcVariable=myfunctionName} )
We create a new dynamic class instance with {}
Insert record with Dapper
Using line is the same. Need to create a list of element to insert even if only one.
connection.execute(“addperson @first name @lastname @email”, people)
People is the list of object: List People=new List() people.Add(new {FirstName=“John”,LastName=“Doe”};
Create instance of a class and set property right away (no constructor)
Person myPerson = new Person {Firstname=“x”, LastName=“y”…};
Search people button function
Private void SearchButtonClick(object sender, eventArgs e) { DataAccess db=new DataAccess(); People=db.GetPeople(seachtextbox.text); }
Dapper: select query with join person-cell Phone
String sql=@”select pe.,ph. from dbo.Person pe left join dbo.Phone ph on pe.CellPhoneId=ph.id;”;
Var people=conn.Query(sql,(person, phone)=> {person.CellPhone=phone; return person;});
display person firstname, last name and phone from people
Foreach( var p in people)
{
Console.WriteLine($”{p.FirstName} {p.LastName} Cell: {p.CellPhone?.CellNumber}”);
}
Dapper: select query with join person-cell Phone with parameter
var p=new { LastName=lastName}; String sql=@”select pe.*,ph.* from dbo.Person pe left join dbo.Phone ph on pe.CellPhoneId=ph.id where p.LastName=@LastName;”; Var people=conn.Query(sql, (person, phone) => {person.CellPhone=phone; return person;},p);
Dapper, multiple sql queries
String sql=”select * from dbo.Person; select * from dbo.Phone;” List people = null; List phones=null; Using(var Lists=conn.QueryMultiple(sql)) { people=Lists.read().ToList(); phones=Lists.Read().Tolist(); }
Dapper, multiple sql queries with parameters: last name and partial phone number
String sql=”select * from dbo.Person where LastName=@LastName; select * from dbo.Phone where PhoneNumber like ‘%’ + PartialPhoneNumber + ‘%’ ;” Var p = new { LastName=lastName; PartialPhoneNumber=partialPhoneNumber; } List people = null; List phones=null; Using(var Lists=conn.QueryMultiple(sql,p)) { people=Lists.read().ToList(); phones=Lists.Read().Tolist(); }
Transaction: Insert person then try to update all id to 1.
String sql=$@ “INSERT INTO dbo.Person (FirstName,LastName) VALUES (@FirstName,@LastName);”;
Var p= new DynamicParameter();
p.Add(“@FirstName”,firstName);
p.Add(“@LastName”,lastName);
conn.Open();
using (var trans =conn.BeginTransaction())
{
Int recordUpdated=conn.execute(sql,p,trans);
Try { conn.Execute(“Update dbo.Person SET id=1”); trans.Commit;}
Catch (Exception ex) { Console.WriteLine($“Error :{ex.Message}“) ; trans.RollBack(); }
}
Define DataTable (firstName, LastName) and put data in it
Private Static DataTable getTroopers() { Var Output=new DataTable(); Output.Columns.Add(“FirstName”,typeof(string)); Output.Columns.Add(“LastName”,typeof(string)); Output.Rows.Add(“John”,”Smith”); Output.Rows.Add(“Lea”,”Doe”); Return Output }
Using get troopers and UDT to insert multiple records
var troopers=getTroopers(); var p =new { people=troopers.AsTableValuedParameter(BasicUDT) }; Int recordAffected=conn.Execute(“dbo.PersonInsert,p,commandType: commandType.StoredProcedure);