Yoo Matsuo
Yoo Matsuo

Reputation: 2363

Is there a way to cast ObjectSet<table1> to ObjectSet<EntityObject>?

I'm trying to make long codes short. The original codes does something following:

using (var context = new DataEntities())
{
context.Table1.Foreach(x =>{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI                    
});

context.Table2.Foreach(x =>
{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI                    
});

context.Table3.Foreach(x =>
{
    // Omit ... updating UI
    DoSomething(x);
    // Omit ... updating UI                    
});
// continue...
}

As you see, there is lots of similar code here. So, I thought I should refactor it though, it's pretty hard for me since I cannot cast context.Table1 to anything, for an example, to cast context.Table1 to ObjectSet<EntityObject> to implement a method which does all the same action for the tables.

I just want to put similar codes into a method, does anyone have a good idea?

Thanks in advance,
Yoo

Upvotes: 1

Views: 781

Answers (2)

Allon Guralnek
Allon Guralnek

Reputation: 16121

Generics?

private void DoSomethingWithAnyTable<T>(ObjectSet<T> table) where T : EntityObject
{
    table.Foreach(x =>{ 
        // Omit ... updating UI 
        DoSomething(x); 
        // Omit ... updating UI                     
    });
}

Then

DoSomethingWithAnyTable(context.Table1);
DoSomethingWithAnyTable(context.Table2);
DoSomethingWithAnyTable(context.Table3);

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062512

You should be able to use .Cast<SomeCommonType> to get an IEnumerable<T> of them? Assuming there is come commonality.

Otherwise; perhaps just IEnumerable? (non-generic)

Upvotes: 2

Related Questions