views:

65

answers:

2

Using EF 4, I have several subtypes of a 'Business' entity (customers, suppliers, haulage companies etc). They DO need to be subtypes. I am building a general viewmodel which calls into a service from which a generic repository is accessed.

As I have 4 subtypes, it would be good to have a 'generic' viewmodel used for all of these. Problem is of course is that I have to call a specific type into my generic repository, for example:

BusinessToRetrieve = _repository
    .LoadEntity<Customer>(o => o.CustomerID == customerID);

It would be good to be able to call <SomethingElse>, somethingElse being one or other of the subtypes), otherwise I shall have to create 4 near identical viemodels, which seems a waste of course! The subtype entity name is available to the viewmodel but I've been unable to figure out how to make the above call convert this into a type. An issue with achieving what I want is that presumably the lambda expression being passed in wouldn't be able to resolve on a 'generic' call ?

A: 

It sounds like you need to make yourself familiar with generics. As a start, you'll be able to write code like this:

class ViewModel<T> where T : Business {
    public void DoSomething(Func<T, bool> predicate) {
        BusinessToRetreive = _repository.LoadEntity<T>(predicate);
    }
}

Then you can say:

ViewModel<Customer> c = new ViewModel<Customer>();
c.DoSomething(o => o.CustomerID == customerID);
Jason
+1  A: 

I'm not sure if this is what you want, but you might be interested in MicroModels

public class EditCustomerModel : MicroModel
{
    public EditCustomerModel(Customer customer, 
                             CustomerRepository customerRepository)
    {
        Property(() => customer.FirstName);
        Property(() => customer.LastName).Named("Surname");
        Property("FullName", () => string.Format("{0} {1}", 
                                           customer.FirstName, 
                                           customer.LastName));
        Command("Save", () => customerRepository.Save(customer));
    }
}
Eduardo Molteni