Joe Slater
Joe Slater

Reputation: 2473

How to convert DbSet to ObservableCollection

I want to create a value converter which will convert DbSet<MyEntity> to ObservableCollection<MyEntity> so that I can bind it easily to a combobox in WPF XAML. I want it to work across all types.

I have tried this so far.

class DbSetToObservableCollectionConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            DbSet<T> d = (DbSet<T>)value; //How do I know what to put in place of T
            return new ObservableCollection<T>(d);
        }
        catch(Exception ex)
        {
            return value;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

This does not work as T is not really a type. Can somebody help me what to do?

Upvotes: 2

Views: 3993

Answers (2)

Oscar Perez
Oscar Perez

Reputation: 111

Having:

 DbSet<Thread> Threads;

Use:

ObservableCollection<Thread> Threads;            

 using (var db = new MyContext())
        {
            Threads =new ObservableCollection<Thread>(db.Threads);
        }

Upvotes: 2

Fede
Fede

Reputation: 44068

Don't do this in a converter. Do it in the ViewModel. That way, your ViewModel will have a strongly typed reference to the DbSet<T> (not just an object) and will know what type T is.

Upvotes: 1

Related Questions