Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection using dapper

Tags:

c#

dapper

I have a problem with my query using dapper, whether someone imagine to help me and say where I'm doing the wrong, is currently showing me an error at the date when I put a breik point, how to correct it properly? thank you all for help

this is my current code

public string GetBezeichnung(int LP, DateTime date)
{
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection())
    {
        connection.ConnectionString = _ConnectionString;
        var output = connection.Query<string>("SELECT ZER_Bezeichnung FROM Z_ERFASSUNG WHERE ZER_LPE = " + LP + " AND ZER_Datum = " + date).FirstOrDefault();
        return output;
    }
}

and this is the result with which I get an error

image description here

like image 315
Michael Avatar asked Aug 30 '18 07:08

Michael


People also ask

What is Dapper SQL?

Dapper is an object–relational mapping (ORM) product for the Microsoft . NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks.


2 Answers

Try parameterizing the query.

public string GetBezeichnung(int LP, DateTime date)
{
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(_ConnectionString))
    {
        connection.Open();
        string sql = @"
SELECT ZER_Bezeichnung 
FROM Z_ERFASSUNG 
WHERE ZER_LPE = @LP
  AND ZER_Datum = @date"
        var output = connection.Query<string>(sql, new { LP = LP, date = date }).FirstOrDefault();
        return output;
    }
}
like image 176
Parrish Husband Avatar answered Oct 19 '22 23:10

Parrish Husband


I agree with @Parrish Husband, but the Second Paramater has to be "Date = date".

In your example there are no ' around the date so AQL thinks its a bunch or things.

Changing it to

var output = connection.Query<string>("SELECT ZER_Bezeichnung FROM Z_ERFASSUNG WHERE ZER_LPE = " + LP + " AND ZER_Datum = '" + date + "'").FirstOrDefault();

will make it work.

like image 38
Shaun Avatar answered Oct 20 '22 00:10

Shaun