Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dapper populate DropDownlist

Tags:

orm

dapper

I have a simple Poco

public virtual short UserID
{
  get;
  set;
}

[Required]
public virtual string UserName
{
  get;
  set;
}
public virtual string Password
{
  get;
  set;
}

public virtual string Email
{
  get;
  set;
}

Im currently Using Dapper ORM.

Does anyone have a good example of how I would query using dapper ORM to create a drop-down-list?

The query should return Key=UserID and Value=UserName in a list so that I can retrieve the keys and populate the DropDownList.

like image 356
user1671707 Avatar asked Apr 19 '26 18:04

user1671707


1 Answers

you can create a class representing the pair:

class SelectItem
{
    public long Key {get;set;}
    public string Value {get;set;}
}

var list = connection.Query<SelectItem>(" select id Key UserName Value from yourtable",null).ToList();

you use the aliases to map the table fields to the class properties names. I'm supposing your table field names are id and UserName, change them according to your case. You should also pay attention to the property types, you can have a bad cast exception if they don't match. ALternatively, you can use the dynamic version:

 var list = connection.Query(" select id Key UserName Value from yourtable",null).ToList();

you obtain a list of dynamics each with property named Key and UserName.

like image 103
Felice Pollano Avatar answered Apr 21 '26 10:04

Felice Pollano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!