Vlad i Slav
Vlad i Slav

Reputation: 61

Entity Framework generic DbSet to List

I'm try to bind generic DbSet to Combobox like this:

public static void BindComboboxByEntity(ComboBox combo, Type type, string displayMember, string valueMember, string orderBy)
{
    if (combo is ComboBox)
        using (var db = new MyDbContext())
        {
            combo.ValueMember = valueMember;
            combo.DisplayMember = displayMember;
            combo.DataSource = db.Set(type).OrderBy(orderBy);
        }
    }

Calling:

BindComboboxByEntity(MyCombo, typeof(MyEntity), "name", "id", "name");

But I know that I need to convert IQueryable to List for binding data to Combobox. How can I doing this?

Upvotes: 1

Views: 1856

Answers (2)

Gabriel Llorico
Gabriel Llorico

Reputation: 1803

if you are passing Type type, try this

var result = db.Set(type).OrderBy(orderByString).ToListAsync();
combo.DataSource = result.Result;

but my suggestion would be pass a generic class/entity

public static void BindComboboxByEntity<T>(ComboBox combo, string displayMember, string valueMember, string orderBy) where T : class
{
   if (combo is ComboBox)
        using (var db = new MyDbContext())
        {
            combo.ValueMember = valueMember;
            combo.DisplayMember = displayMember;
            combo.DataSource = db.Set<T>().OrderBy(orderBy);
        }

}

then pass it as

BindComboboxByEntity<MyEntity>(MyCombo, "name", "id", "name");

Upvotes: 2

Pac0
Pac0

Reputation: 23174

Note that the IQueryable still represent a "query" that has (in general) not been executed. You need to actually materialize the query (with a ToList() for instance)

combo.DataSource = db.Set(type).OrderBy(orderBy).ToList();

Note : You will need

using System.Linq;

Upvotes: 3

Related Questions